Skip to content

Dashboard Agent: investigations, watches, alerts, and notifications - #4418

Draft
kathiekiwi wants to merge 168 commits into
mainfrom
feat/dashboard-agent-flows
Draft

Dashboard Agent: investigations, watches, alerts, and notifications#4418
kathiekiwi wants to merge 168 commits into
mainfrom
feat/dashboard-agent-flows

Conversation

@kathiekiwi

@kathiekiwi kathiekiwi commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator

An AI assistant in a side panel on every dashboard page, behind the dashboard-agent feature flag. It reads runs, errors, queues, deploys and health through the public API (read-only, delegated user token), answers with rich cards, and can keep watching things after the conversation ends.

What's inside

  • Foundation@internal/dashboard-agent-contracts (trigger:// URI grammar, intents, watch specs, block envelope), investigations + watches tables, head-start reliability fix, eval sample-rate gate.
  • Reportsget_report renders the deterministic health report as a card (metric grid, sparklines, Next steps button row); stale telemetry is flagged and never trusted for advice.
  • Investigate — hypothesis-driven investigation on a live card with system-owned identity and revisions; entry buttons on failed runs, errors, and backed-up queues; code-grounded when a repo is connected.
  • Watch — durable conditions checked on a schedule with zero LLM in the ticks (run start/finished, backlog drain, error recurrence, health recovery); the fire wakes the chat with a toned banner.
  • Alerts & notifications — a new DASHBOARD_AGENT_WATCH alert type on the standard channels with one-click unsubscribe; the agent offers, lists and disables subscriptions on request; ungated in-dashboard signal: persistent toast, unread dot on the chat launcher, unread-first history with per-chat status icons.
  • Tooling — navigation, TRQL queries with live charts, deploy correlation, docs answers, suggested prompts; golden eval suite; seeder for a live playground project (db:seed:agent-examples, with --heartbeat / --degrade / --recover for demos).

How to review

GUIDEBOOK.md — 10-minute local setup and a hands-on walkthrough of every case. Component gallery at /storybook/agent-ui.

Notes

  • Everything is gated by canAccessDashboardAgent; no behavior change with the flag off.
  • The seeder's --heartbeat mode is a review-stand crutch and will be removed before merge.

ericallam added 30 commits July 13, 2026 20:38
…signals

Gauges are read inside the enqueue/dequeue Lua and returned on the script reply
as a 2-tuple; counters are cumulative odometers. The run-queue Redis carries no
metrics stream of its own.
…counters

entryOrderKey returns a string built with BigInt math so ordering stays correct at real epoch magnitudes. Odometer keys are namespaced by definition name. The consumer reports null lag for a missing consumer group instead of 0, and empty gauge values parse as NaN rather than 0.
…ng order keys

The wait-time quantile materialized view now excludes wait_ms = 0 rows so it matches the count aggregation. order_key accepts a string or a number. Migration comments no longer contain semicolons that split the migration into invalid statements.
…rride

The queues list tolerates a metrics query failure by rendering without metrics and logging a warning. UsageSparkline renders its total override even when every bucket is zero. The queue detail page returns 404 and its loader skips the metrics query when the feature flag is off. The seed script validates bucket size and only writes ClickHouse against a local host.
A bucket-led ORDER BY DESC combined with fillGaps emitted an ascending WITH FILL (positive step, ascending bounds), which produces invalid or empty fills. Skip the gap-fill rewrite for descending orders and let the plain descending query stand. Adds a DESC fillGaps test.
Packs the stream sequence with a 1e6 factor (was 1e5) so up to 1M entries per millisecond per shard fit before a seq could spill into the next millisecond's range, far above what a single Redis stream can produce. ms*1e6 stays within UInt64. Also fixes the webapp mapping test that still expected a numeric order_key after the switch to a BigInt-derived string.
The queues list and queue detail pages now use the shared TimeFilter (any preset period or a custom date range) and everything on the page follows it: header tiles, per queue metric columns, charts, and stats. The custom period buttons, hand rolled chart cards, and duplicated metric fetch loops are replaced by the ChartCard and Chart primitives, UsageSparkline, and a shared useMetricResourceQuery hook. The ClickHouse list queries take an explicit end bound so fixed ranges query only their window.
Queries using deltaSumTimestampMerge failed with an unknown function error, which broke the queue detail stats and the started counts on the built in Queues dashboard.
The queues list header tiles now render the same line chart, grid, and tooltip as the rest of the metrics charts instead of a row sparkline, with the headline value in the tile header. The env saturation tile draws the environment concurrency limit and burst limit as labeled reference lines. Chart tooltips keep a gap between the series label and the value, and the shared line chart gains showDots and referenceLines options.
Adds an Allocation tab to the Queues page (behind the queue metrics UI flag): overview cards, a burst-aware capacity bar showing each queue allocation and its live usage in a distinct color, an inline-editable limits table with per-queue locks, load-weighted auto-balance, and a review dialog that bulk-applies limits as overrides through the existing concurrency system.

The queue list now defaults to Busiest ordering (with Backlog and Name options). ClickHouse ranks queues by activity over the last 15 minutes and returns just the requested page of names, so the cost per page is one small aggregate regardless of environment size; idle queues follow in name order and any failure falls back to name ordering. The classic page keeps plain name order.
The fallback WHERE injection only targeted the top-level SELECT, so a
query shaped as an outer aggregation over a FROM subquery failed to
compile: the time column only exists inside the subquery. Descend into
the subquery so the fallback lands next to the table reference.
Adds two rollups fed from the raw landing table: a per-queue 5-minute
tier and an environment-level 1-minute tier (gauges plus TDigest wait
quantiles). Ranking now reads the 5m tier and returns the page and the
ranked total in one windowed query instead of two scans.

The 5m materialized view reads raw rather than cascading off the 10s
table: deltaSumTimestamp states hold a single first/last segment, so
merging states in an MV's hash-ordered GROUP BY double-counts bridging
spans. For the same reason the env tier carries no counter columns, and
env-wide counter totals must group by queue before summing.
The built-in queues dashboard's enqueued vs started chart merged counter
states across queues, which mixes unrelated cumulative counters and
returns wrong totals; it now merges per queue and sums outside. Env
header tiles and saturation charts read the environment rollup, so their
cost no longer scales with queue count, and coarse-bucket ranges are
served from the 5m rollup automatically. Queue list ranking runs as one
query, time bounds are aligned to the bucket grid, and repeated
auto-refresh reads share ClickHouse query-cache entries.
… rollup

The env rollup's win comes from dropping the queue dimension, not from
coarser buckets: row count is queue-independent (~8640/day/env), so full
10-second granularity stays cheap at any range. Env header tiles and
saturation charts now resolve short-range detail exactly like the
per-queue charts, and the current-value tiles read the latest 10-second
bucket instead of a minute-wide one.
The simulator's --reset only cleared the raw and 10s tables, leaving
stale rows in the 5m and env rollups. It also force-merges the rollups
after seeding so current-value widgets read cleanly.
…aks plainly

One conversational message with the watch's note, a lime CTA, and the
same skeleton as the billing-limit email; the fielded fact sheet is
gone and the unsubscribe link keeps its wiring with footer styling.
'Watch update — all clear / needs your attention', toned by kind; the
identity moves to the details line and the subject follows suit.
@changeset-bot

changeset-bot Bot commented Jul 29, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 3106ce7

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 60496582-6e60-4341-9e10-ab8e5014eaa6

📥 Commits

Reviewing files that changed from the base of the PR and between 7abce81 and 3106ce7.

📒 Files selected for processing (3)
  • apps/webapp/app/components/dashboard-agent/AgentChart.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/webapp/app/components/dashboard-agent/AgentChart.tsx
📜 Recent review details
⏰ Context from checks skipped due to timeout. (33)
  • GitHub Check: internal / 🧪 Unit Tests: Internal
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
  • GitHub Check: sdk-compat / Node.js 20.20 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
  • GitHub Check: sdk-compat / Node.js 26.4 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Node.js 24.18 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-ubuntu-latest-x64-4x - npm)
  • GitHub Check: sdk-compat / Deno Runtime
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-ubuntu-latest-x64-4x - pnpm)
  • GitHub Check: sdk-compat / Node.js 22.23 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Cloudflare Workers
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - npm)
  • GitHub Check: sdk-compat / Bun Runtime
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - pnpm)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
  • GitHub Check: runops-guard / runops-guard
  • GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
  • GitHub Check: code-quality / code-quality
  • GitHub Check: 🛡️ E2E Auth Tests (full)
  • GitHub Check: Analyze (javascript-typescript)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead

**/*.{ts,tsx}: Prefer static imports over dynamic import(); use dynamic imports only for unresolvable circular dependencies, genuine performance code splitting, or conditional runtime loading.
Import Trigger.dev tasks from @trigger.dev/sdk; never use @trigger.dev/sdk/v3 or deprecated client.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with // @Crumbs or blocks with `// `#region` `@crumbs, and strip them before merging.

Files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
{packages/core,apps/webapp}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use zod for validation in packages/core and apps/webapp

Files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use function declarations instead of default exports

Files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
apps/webapp/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)

apps/webapp/**/*.{ts,tsx}: Access environment variables through the env export of env.server.ts instead of directly accessing process.env
Use subpath exports from @trigger.dev/core package instead of importing from the root @trigger.dev/core path

Do not reintroduce the removed v1 execution path; RunEngineVersion.V1 branches may only reject or finalize gracefully so v3 clients receive a clean 4xx, never a 5xx.

Files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
apps/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

For apps, use typecheck for verification and never use build as the correctness check.

Files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
apps/webapp/app/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)

apps/webapp/app/**/*.{ts,tsx}: For dashboard changes, visually verify the running Remix app with Chrome DevTools MCP, using snapshots, screenshots, interaction, and console-message checks as appropriate.
Use useCallback and useMemo only for context provider values, expensive derived data used as a dependency, or stable references required by dependency arrays; do not wrap ordinary event handlers or trivial computations.
Use named constants for sentinel or placeholder values instead of scattering raw string literals across comparisons.

Files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
🧠 Learnings (16)
📚 Learning: 2026-02-11T16:37:32.429Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3019
File: apps/webapp/app/components/primitives/charts/Card.tsx:26-30
Timestamp: 2026-02-11T16:37:32.429Z
Learning: In projects using react-grid-layout, avoid relying on drag-handle class to imply draggability. Ensure drag-handle elements only affect dragging when the parent grid item is configured draggable in the layout; conditionally apply cursor styles based on the draggable prop. This improves correctness and accessibility.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-07-28T21:57:20.061Z
Learnt from: samejr
Repo: triggerdotdev/trigger.dev PR: 4411
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.team/route.tsx:818-843
Timestamp: 2026-07-28T21:57:20.061Z
Learning: When using Radix UI `DialogClose` with `asChild` (e.g., Trigger.dev dashboard components), note that it injects `type="button"` into its child via `Slot`. If the child is a local `Button` that forwards its `type` prop to the native `<button>`, then placing it inside a `<form>` will *not* submit unless you explicitly set `type="submit"` (or otherwise override the injected type / wire up submission behavior). Review form actions to ensure the intended submit vs non-submit behavior is preserved.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-13T19:53:13.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3937
File: packages/trigger-sdk/skills/realtime-and-frontend/SKILL.md:258-260
Timestamp: 2026-06-13T19:53:13.759Z
Learning: When reviewing code that uses `trigger.dev/react-hooks`’s `useRealtimeRun`, preserve the call signature where the first argument is the full realtime handle object (not `handle.id`). This is intentional to maintain type-safety and is consistent with the official docs; do not suggest changing the first argument from the handle object to `handle.id`.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-17T17:13:49.929Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3948
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions.$bulkActionParam/route.tsx:48-62
Timestamp: 2026-06-17T17:13:49.929Z
Learning: In triggerdotdev/trigger.dev, within `dashboardLoader`/`dashboardAction` (or similar context resolver code) whenever you resolve an organization ID from an organization slug for RBAC/enterprise authorization scope, always read from the primary Prisma client (`prisma`), not `$replica`. Using `$replica` can hit replica-lag and cause the RBAC lookup/authorization to run without the correct org scope (bypassing intended role enforcement). Implement the slug→org lookup with `prisma.organization.findFirst(...)` (or equivalent primary-client query) and add an inline comment documenting why the primary client is required (replica lag could lead to unscoped RBAC checks).

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-23T13:04:21.413Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4023
File: apps/webapp/app/services/upsertBranch.server.ts:14-18
Timestamp: 2026-06-23T13:04:21.413Z
Learning: In TypeScript, it’s valid to `import { type X }` and then use `typeof X` in a type-only position, e.g. `type Alias = z.infer<typeof X>`. The `type` modifier suppresses the runtime import, but the type checker still has the full exported type so `z.infer<typeof X>` can resolve correctly. In code reviews, don’t flag this as a TypeScript compile error as long as `typeof X` is used in a type context (e.g., with `z.infer`, `type` aliases, generics), not as a runtime value.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-04-16T14:21:15.229Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3368
File: apps/webapp/app/components/logs/LogsTaskFilter.tsx:135-163
Timestamp: 2026-04-16T14:21:15.229Z
Learning: When rendering lists of task registry items in apps/webapp (e.g., <SelectItem /> rows) and using `key={item.slug}`, do not flag it as potentially non-unique. In trigger.dev’s `TaskIdentifier` table, the DB constraint `@unique([runtimeEnvironmentId, slug])` guarantees `slug` is unique within a given runtime environment, so `item.slug` is safe as the React key as long as the list is derived from that registry/constraint (and not from a legacy query that could produce duplicate slugs).

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-05-08T21:00:20.973Z
Learnt from: samejr
Repo: triggerdotdev/trigger.dev PR: 3538
File: apps/webapp/app/components/primitives/Resizable.tsx:60-78
Timestamp: 2026-05-08T21:00:20.973Z
Learning: In the triggerdotdev/trigger.dev codebase, treat Zod as a boundary validation tool (API handlers, request/response validation, and storage/DB read/write validation), not as inline render-time validation inside React components/primitive UI code. For render-time guards, prefer small manual type-narrowing checks (e.g., a short predicate like ~10–20 lines) over importing Zod into UI primitives, to avoid per-render schema-parse overhead and unnecessary abstraction. Use the manual guard approach unless you truly need schema validation at a boundary; only then introduce Zod.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-25T18:21:55.847Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/invite-resend.tsx:0-0
Timestamp: 2026-06-25T18:21:55.847Z
Learning: In the triggerdotdev/trigger.dev Zod 4 migration, avoid importing from the root package `conform-to/zod` in webapp code. It can resolve to the Zod 3 build and may crash at module load under Zod 4. When reviewing TypeScript/TSX files in `apps/webapp`, prefer importing from the Zod 4 subpath `conform-to/zod/v4` for Zod 4-compatible schemas/types.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-05-12T21:04:05.815Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3542
File: apps/webapp/app/components/sessions/v1/SessionStatus.tsx:1-3
Timestamp: 2026-05-12T21:04:05.815Z
Learning: In this Remix + TypeScript codebase, do not flag a server/client boundary violation when a file imports only types from a module matching `*.server`.

Specifically, it’s safe to import types using `import type { Foo } from "*.server"` or `import { type Foo } from "*.server"` because TypeScript erases type-only imports at compile time and they emit no JavaScript, so they won’t cross the Remix server/client bundle boundary.

Only raise the boundary concern for value imports (e.g., `import { Foo }` without `type`, or `import Foo`), since those produce JavaScript output.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-25T18:21:51.905Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/invite-revoke.tsx:0-0
Timestamp: 2026-06-25T18:21:51.905Z
Learning: During the Zod v4 migration in the triggerdotdev/trigger.dev webapp, ensure any imports from `conform-to/zod` use the Zod-4 subpath: `conform-to/zod/v4` (e.g., `import { parseWithZod } from "conform-to/zod/v4"`). Do not import from the package root `conform-to/zod`, because it is the Zod 3 implementation and may load Zod-3-only symbols (e.g., `ZodBranded`, `ZodEffects`), which can throw at module load (notably with `zod4.4.3`). This should be enforced across `apps/webapp/**/*` where helpers like `parseWithZod` and `conformZodMessage` are used.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-07-03T17:10:21.498Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 4148
File: apps/webapp/app/models/orgMember.server.ts:149-168
Timestamp: 2026-07-03T17:10:21.498Z
Learning: In triggerdotdev/trigger.dev, `User.email` (Prisma schema: `internal-packages/database/prisma/schema.prisma`) currently does NOT use `citext` and does NOT have a `lower(email)` functional unique index. Therefore, do not introduce Prisma queries like `where: { email: { equals: <value>, mode: "insensitive" } }` (or any case-insensitive lookup) against `User.email`, because it can force sequential scans of the `users` table under load. During review, ensure email is normalized (e.g., lowercased/trimmed) before both writes and subsequent lookups, and if true case-insensitive behavior/uniqueness is required, implement it via a separate app-wide migration (e.g., switch to `citext` and/or add a functional unique index with backfill) rather than bolting it onto individual feature PRs.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-25T18:21:54.729Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/confirm-basic-details.tsx:0-0
Timestamp: 2026-06-25T18:21:54.729Z
Learning: For Remix + TypeScript files that use Conform v1 (conform-to/react) and its getInputProps helper, when you intend to suppress the helper-provided default value for non-checkbox/non-radio inputs (e.g., hidden inputs managed via an explicit value prop), use the Conform v1 option key `value: false`. Do not recommend `defaultValue: false` here, because `defaultValue` is not a valid option key for these input types in Conform v1 typings.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
🔇 Additional comments (2)
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx (1)

166-195: LGTM!

Also applies to: 277-332

apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx (1)

40-40: LGTM!

Also applies to: 247-251


Walkthrough

This PR introduces a comprehensive Dashboard Agent feature: a new contracts package defining shared schemas for view blocks, intents, page context, watches, and trigger:// URIs; a dedicated database package for chats, investigations, and watches; core agent tool/prompt logic including investigation rendering, docs search, and navigation intents; a watch-tick lifecycle with checks, alerts (email/Slack/webhook), and unsubscribe flows; new API routes for watches, alerts, queue metrics, and run diagnostics; a redesigned chat panel UI with investigation/report/watch cards, suggested prompts, and unread-wake notifications; a Storybook demo gallery with screenshot tooling; seed scripts; and removal of "Docs" links from numerous page headers across the webapp.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description does not follow the required template and omits the issue link, checklist, testing, changelog, and screenshots sections. Rewrite it to match the template: add Closes #, complete the checklist, include testing steps, a changelog summary, and screenshots or a placeholder.
Docstring Coverage ⚠️ Warning Docstring coverage is 55.84% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main dashboard-agent feature work.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/dashboard-agent-flows

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…t button; URLs are links

The prompt now treats earlier turns' pages as history — deictic
questions re-read the current page every turn, and page explanations
end with a matching docs link. The report's contact action falls back
to the contact page as a real external button instead of an ask
round-trip, and answers that point at a URL carry it as a link.
…ress line, wake toast opens its chat as an agent Callout

- navigate intents and navigate_to outputs resolve trigger:// URIs
  server-side and navigate in place; same-origin citation buttons
  navigate instead of opening a new tab.
- The transcript autoscrolls on send and follows streaming near the
  bottom; a store-order stable merge stops messages landing mid-chat
  after a page change (server-side single-read follow-up noted).
- The generic Working line yields to a tool-specific one.
- The wake toast is the new agent Callout variant (chat icon) and opens
  the exact chat that woke.
Base automatically changed from feat/queue-metrics-and-health to main July 29, 2026 15:45
An in-flight tool call now shows a compact pill (per-tool phrase +
spinner, watch-chip visual language) instead of raw streaming JSON —
covering render_view and get_report, the biggest offenders. Completed
and error states render as before; gallery in-flight examples reworked
and a pill line-up section added.
The answer is the prose and the cards, never the input/output plumbing:
a landed call disappears (the pill was its only trace), and only a
FAILED call keeps its error row. Gallery example reworked accordingly.
Wakes are wake-shaped (banner renders), no prose points at tool rows
that no longer render, footer-era phrasing removed, the four-wake
variation matrix became one coherent story, and tests now enforce all
of it (wake ids parse via the real WakeBanner, removed-UI phrases are
banned).
Offering to fetch what a tool can fetch now is banned; 'how do I check
X' about the user's project gets both the how-to and the actual check;
only genuinely unreachable steps (their infra, their code, external
pages) go to the user, clearly separated.
…flows

# Conflicts:
#	.changeset/report-health.md
#	.server-changes/agent-detail-metrics-layout.md
#	.server-changes/paginate-concurrency-keys-table.md
#	.server-changes/queue-metrics-dashboard.md
#	apps/webapp/app/components/dashboard-agent/AgentChart.tsx
#	apps/webapp/app/components/metrics/MiniLineChart.tsx
#	apps/webapp/app/components/query/QueryEditor.tsx
#	apps/webapp/app/env.server.ts
#	apps/webapp/app/hooks/useMetricResourceQuery.ts
#	apps/webapp/app/presenters/v3/QueueListPresenter.server.ts
#	apps/webapp/app/presenters/v3/QueueMetricsPresenter.server.ts
#	apps/webapp/app/presenters/v3/RunQueueMetricsPresenter.server.ts
#	apps/webapp/app/presenters/v3/reports/health/health-data.ts
#	apps/webapp/app/presenters/v3/reports/health/health-messages.ts
#	apps/webapp/app/presenters/v3/reports/health/health.ts
#	apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.query/ExamplesContent.tsx
#	apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.query/TableSchemaContent.tsx
#	apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.queues/route.tsx
#	apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.queues_.$queueParam/route.tsx
#	apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.tasks.standard.$taskParam/route.tsx
#	apps/webapp/app/routes/api.v1.query.schema.ts
#	apps/webapp/app/routes/resources.metric.tsx
#	apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.query.ai-generate.tsx
#	apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam.spans.$spanParam/route.tsx
#	apps/webapp/app/routes/resources.queues.concurrency-keys.ts
#	apps/webapp/app/services/queryService.server.ts
#	apps/webapp/app/v3/querySchemas.ts
#	apps/webapp/app/v3/queueMetrics.server.ts
#	apps/webapp/test/reportHealth.test.ts
#	internal-packages/clickhouse/src/client/tsql.ts
#	internal-packages/run-engine/src/engine/systems/enqueueSystem.ts
#	internal-packages/tsql/src/query/schema.ts
@pkg-pr-new

pkg-pr-new Bot commented Jul 30, 2026

Copy link
Copy Markdown

Open in StackBlitz

@trigger.dev/build

npm i https://pkg.pr.new/@trigger.dev/build@5895609

trigger.dev

npm i https://pkg.pr.new/trigger.dev@5895609

@trigger.dev/core

npm i https://pkg.pr.new/@trigger.dev/core@5895609

@trigger.dev/python

npm i https://pkg.pr.new/@trigger.dev/python@5895609

@trigger.dev/react-hooks

npm i https://pkg.pr.new/@trigger.dev/react-hooks@5895609

@trigger.dev/redis-worker

npm i https://pkg.pr.new/@trigger.dev/redis-worker@5895609

@trigger.dev/rsc

npm i https://pkg.pr.new/@trigger.dev/rsc@5895609

@trigger.dev/schema-to-json

npm i https://pkg.pr.new/@trigger.dev/schema-to-json@5895609

@trigger.dev/sdk

npm i https://pkg.pr.new/@trigger.dev/sdk@5895609

commit: 5895609

… uses the tenancy-scoped list signature

The suite pinned a migration list that stopped before last_read_at
(42703 on CI) and two tests still called listActiveWatchesForChats with
the pre-tenancy array signature. Migrations are now read from the
folder so a new one can't silently stale the schema.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsx (1)

95-112: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard getPromotedDashboardAgentPrompt against failures, and skip it when access is already false.

This loader backs the entire env layout (Outlet wraps every page under this environment), so it runs on nearly every navigation. getPromotedDashboardAgentPrompt is called unconditionally and unguarded — if flag evaluation/parsing ever throws, it takes down the whole environment layout for a feature that's purely cosmetic (a suggested-prompt chip). It's also wasted work whenever hasDashboardAgentAccess is false, since DashboardAgent never consumes promotedPrompt in that case (it early-returns children without rendering the panel).

🛡️ Proposed fix: gate on access and fail closed
-  const promotedDashboardAgentPrompt = await getPromotedDashboardAgentPrompt({
-    orgFeatureFlags: (project.organization.featureFlags as Record<string, unknown>) ?? {},
-  });
+  const promotedDashboardAgentPrompt = hasDashboardAgentAccess
+    ? await getPromotedDashboardAgentPrompt({
+        orgFeatureFlags: (project.organization.featureFlags as Record<string, unknown>) ?? {},
+      }).catch((error) => {
+        logger.error("Failed to resolve promoted dashboard agent prompt", { error });
+        return undefined;
+      })
+    : undefined;
🟡 Minor comments (13)
apps/webapp/seed-agent-examples.mts-1598-1614 (1)

1598-1614: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

?.value ? … : undefined collapses a legitimate zero into the fallback.

pending, donePerMin, triggeredPerMin and drainMinutes all treat a reported 0 as "absent" and fall back to the STORY.* constants. On a recovered or quiet stand the card would read 0 pending while the prose quotes 4,812 — the exact disagreement this function exists to prevent. Use a nullish check instead.

🐛 Guard on presence, not truthiness
-    pending: metric("pending")?.value ? Math.round(metric("pending")!.value) : undefined,
+    pending: metric("pending")?.value != null ? Math.round(metric("pending")!.value) : undefined,
     worstQueueShare: flow?.attribution?.dim === "queue" ? flow.attribution.share : undefined,
-    donePerMin: vm.facts?.throughput?.donePerMin
+    donePerMin: vm.facts?.throughput?.donePerMin != null
       ? Math.round(vm.facts.throughput.donePerMin)
       : undefined,
-    triggeredPerMin: vm.facts?.throughput?.triggeredPerMin
+    triggeredPerMin: vm.facts?.throughput?.triggeredPerMin != null
       ? Math.round(vm.facts.throughput.triggeredPerMin)
       : undefined,
-    drainMinutes: drain?.value ? Math.round(drain.value) : undefined,
+    drainMinutes: drain?.value != null ? Math.round(drain.value) : undefined,
apps/webapp/seed-queue-metrics.mts-581-597 (1)

581-597: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

DELETE without mutations_sync races the seeding insert that follows.

--reset runs these deletes and then line 941 inserts immediately. The sibling seeder guards the identical sequence with SETTINGS mutations_sync = 2 and explains why: left asynchronous, the re-seed races its own predecessor and leaves a second copy of the data behind. Worth setting async_insert: 0 on line 572 too, so the rows are visible to the OPTIMIZE … FINAL calls on lines 949-952.

🐛 Make the reset finish before seeding
     await raw.command({
-      query: `DELETE FROM trigger_dev.${table} WHERE environment_id = '${environmentId}'`,
+      query: `DELETE FROM trigger_dev.${table} WHERE environment_id = '${environmentId}' SETTINGS mutations_sync = 2`,
     });
apps/webapp/seed-agent-examples-chats.mts-338-339 (1)

338-339: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use the COMPLETED_WITH_ERRORS status literal in the TRQL query.

Failed is not a standard run status in Trigger.dev TRQL; use status = 'COMPLETED_WITH_ERRORS' so the seeded failed runs are counted.

apps/webapp/seed-queue-metrics.mts-1-6 (1)

1-6: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Keep this seeder consistent with seed-agent-examples.mts's documented interop pattern.

seed-agent-examples.mts disables the sibling import-entry CommonJS boundary instead of running into the documented named-import loading failure, so this script should use the same default-binding import/interworking pattern.

internal-packages/dashboard-agent-contracts/src/blocks.ts-133-146 (1)

133-146: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Require http(s) on docs action targets.

target is documented as “an https URL” for docs actions, but the schema accepts any string. Since this field is LLM-authored UI input, prefer narrowing it to http:// or https:// URLs in the schema rather than leaving the contract to later validation.

apps/webapp/app/services/dashboardAgentWatchChecks.ts-146-175 (1)

146-175: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Make unreliable queued wait labels include the stale-first-enqueue caveat.

For WAITING_TO_RESUME / RETRYING_AFTER_FAILURE / PAUSED, run.queuedAt is not a current queue entry, but this path still emits waitBasis: "queued_at" and a confident queued for … label. Bake the caveat into the label or omit the label when queueWaitReliable is false so it can’t be surfaced as a current wait time downstream.

♻️ Make the label carry its own caveat
   if (run.queuedAt) {
     const waitMs = Math.max(0, end.getTime() - run.queuedAt.getTime());
     return {
       waitMs,
       waitBasis: "queued_at",
-      waitLabel: `queued for ${formatMs(waitMs)}`,
+      waitLabel: queueWaitReliable
+        ? `queued for ${formatMs(waitMs)}`
+        : `time since first enqueue: ${formatMs(waitMs)}`,
       queueWaitReliable,
     };
   }
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx-163-180 (1)

163-180: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

CitationButton renders different elements on server vs client.

path is always null during SSR, so the server emits a LinkButton anchor while the first client render emits a Button — a hydration mismatch for every same-origin citation. Compute the path from sameOriginPath after mount (or keep one element type and branch inside onClick).

♻️ One option: single element, branch on click
 function CitationButton({ url, label }: { url: string; label: string }) {
   const navigate = useNavigate();
-  const path = typeof window === "undefined" ? null : sameOriginPath(url, window.location.origin);
-
-  if (path) {
-    return (
-      <Button variant="docs/small" LeadingIcon={BookOpenIcon} onClick={() => navigate(path)}>
-        {label}
-      </Button>
-    );
-  }
-
   return (
-    <LinkButton to={url} variant="docs/small" LeadingIcon={BookOpenIcon}>
+    <LinkButton
+      to={url}
+      variant="docs/small"
+      LeadingIcon={BookOpenIcon}
+      onClick={(event) => {
+        const path = sameOriginPath(url, window.location.origin);
+        if (!path) return;
+        event.preventDefault();
+        navigate(path);
+      }}
+    >
       {label}
     </LinkButton>
   );
 }
apps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsx-166-189 (1)

166-189: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Post-mutation reloads can coalesce onto a pre-mutation request.

loadHistory returns the in-flight promise, so the void loadHistory() calls in deleteChat (Line 422) and cancelWatch (Line 452) can piggyback on a GET that was issued before the POST landed and re-render the stale list — the deleted chat reappears, or the cancelled watch chip comes back, until something else triggers a reload. Chain a fresh request after the in-flight one instead of returning it.

🐛 Sketch: let callers ask for post-mutation freshness
-  const loadHistory = useCallback(async () => {
-    if (historyInFlight.current) return historyInFlight.current;
+  const loadHistory = useCallback(async (options?: { fresh?: boolean }) => {
+    if (historyInFlight.current) {
+      // A reload after a mutation must not adopt a request that was already
+      // in flight before it — that result predates the change.
+      if (!options?.fresh) return historyInFlight.current;
+      await historyInFlight.current;
+    }
     const request = (async () => {

Then call void loadHistory({ fresh: true }) from deleteChat and cancelWatch.

apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx-161-177 (1)

161-177: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

An enabled button that does nothing is a real click target outside the gallery.

useRunPath returns undefined whenever org/project/env context is missing — the storybook gallery is one such case, but any future host without that context is another. A user clicking gets silence with no feedback. Prefer disabled (or a tooltip explaining why) so the inert state is honest, and keep the gallery's visual review by passing an explicit prop rather than inferring it from missing context.

apps/webapp/test/dashboardAgentWatchChecks.test.ts-123-134 (1)

123-134: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the label in the stale-queuedAt case — that's the invariant this file exists to pin.

The header calls out the wait label as the thing that must never call a time-from-creation a queue wait, but this test only checks queueWaitReliable and waitBasis. A regression that emitted "queued for 10m" for an untrustworthy queuedAt on a resumed run would still pass. Add the label (and the result) assertion.

💚 Proposed addition
     expect(outcome.facts.queueWaitReliable).toBe(false);
     expect(outcome.facts.waitBasis).toBe("queued_at");
+    expect(outcome.result).toBe("pending");
+    // Reliability is false, so the label must not claim a queue wait.
+    expect(outcome.facts.waitLabel).not.toMatch(/queued for/);
internal-packages/dashboard-agent/src/tools.ts-429-448 (1)

429-448: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Wrap the body read so an aborted/interrupted response doesn't escape as a throw.

The fetch call is guarded but await res.text() on Line 431 is not. If the 30s abort fires while the body is streaming (or the connection resets mid-body), this rejects and the throw escapes searchTriggerDocs, breaking the documented "returns { error }" contract that search_docs relies on.

🛡️ Proposed fix
   if (!res.ok) return { error: `The docs search failed (status ${res.status}).` };
 
-  const body = await res.text();
+  let body: string;
+  try {
+    body = await res.text();
+  } catch (error) {
+    return { error: `Couldn't read the docs response: ${(error as Error).message}` };
+  }
   let payload: any;
internal-packages/dashboard-agent/src/tools.ts-872-883 (1)

872-883: 🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

list_errors doesn't clamp period, unlike list_runs and list_deploys.

Lines 845 and 1096 both run the model-supplied period through clampPeriod; Line 877 forwards it raw. Unless the errors route clamps server-side, the model can request an unbounded window here.

♻️ Proposed fix
       execute: async ({ status, taskIdentifier, search, period, limit }) => {
+        const effectivePeriod = period ? clampPeriod(period) : undefined;
         const sp = new URLSearchParams();
         if (status) sp.append("filter[status]", status);
         if (taskIdentifier) sp.append("filter[taskIdentifier]", taskIdentifier);
         if (search) sp.append("filter[search]", search);
-        if (period) sp.append("filter[period]", period);
+        if (effectivePeriod) sp.append("filter[period]", effectivePeriod);
apps/webapp/app/routes/api.v1.queues.$queueParam.metrics.ts-72-78 (1)

72-78: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Rounding endMs up with Math.ceil includes future time in the averaged window.

Because endMs is rounded up to the next bucket boundary, it can be ahead of Date.now() by up to bucketSeconds (as much as ~1/12 of the requested period). startedPerMin and other rate fields then divide the real (bounded) count by a window that partly hasn't happened yet, systematically under-reporting throughput/rate by the same proportion. Math.floor gives identical cache-alignment benefits without ever querying/averaging over future time.

🐛 Proposed fix
-    const endMs = Math.ceil(Date.now() / (bucketSeconds * 1000)) * bucketSeconds * 1000;
+    const endMs = Math.floor(Date.now() / (bucketSeconds * 1000)) * bucketSeconds * 1000;

Also applies to: 124-126

🧹 Nitpick comments (32)
apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx (1)

12-30: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate chart-card frame markup — parameterize rows instead of reimplementing the frame for the empty state.
DemoChartCard hardcodes rows={demoChart.rows} with no way to override it, so the gallery's empty-chart state had to copy the entire border/title-strip/height JSX just to pass rows={[]}.

  • apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx#L12-L30: accept an optional rows prop (defaulting to demoChart.rows) so callers can override the dataset.
  • apps/webapp/app/routes/storybook.agent-ui/route.tsx#L300-L317: replace EmptyChartCard's duplicated JSX with <DemoChartCard rows={[]} /> (or equivalent) once the prop exists.
apps/webapp/app/routes/storybook.agent-ui/route.tsx (1)

397-436: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider deriving untrustworthyReport via the real stale-guard function rather than hand-rolling its output shape.

The comment above this block states it's "Derived exactly the way applyStaleGuard does it," but the code manually reconstructs the transformation instead of calling that function. If applyStaleGuard (or equivalent) is exported and importable here, calling it directly would guarantee this fixture never drifts from the real stale-telemetry behavior it's meant to demonstrate.

Please confirm whether the health report's stale-guard transformation (referenced as applyStaleGuard) is exported in a form importable from this route (e.g. from apps/webapp/app/presenters/v3/reports/health/health.ts), so this fixture could call it directly instead of duplicating its logic.

apps/webapp/app/components/dashboard-agent/demo/demo.test.ts (1)

34-39: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

The isolation guard misses side-effect and dynamic imports.

importSpecifiers only matches … from "x", so import "~/foo.server" and await import("~/db.server") slip through the very check on lines 369-378 that exists to catch them.

♻️ Broaden the specifier scan
-/** Every import specifier in a file, from both `import` and `export … from`. */
+/** Every module specifier in a file: `from "x"`, `import "x"` and `import("x")`. */
 function importSpecifiers(source: string): string[] {
-  return [...source.matchAll(/(?:import|export)[\s\S]*?from\s+["']([^"']+)["']/g)].map(
-    (match) => match[1]!
-  );
+  return [
+    ...source.matchAll(/from\s+["']([^"']+)["']/g),
+    ...source.matchAll(/\bimport\s*\(\s*["']([^"']+)["']/g),
+    ...source.matchAll(/\bimport\s+["']([^"']+)["']/g),
+  ].map((match) => match[1]!);
 }
apps/webapp/seed-agent-examples-chats.mts (1)

257-257: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Import VIEW_BLOCK_VERSION instead of hardcoding version: 1.

The demo fixtures stamp the envelope from the contracts constant; these seeded blocks hardcode 1. If the contract version is bumped, the strict envelope schema rejects these blocks and the cards silently degrade to plain tool rows — exactly the failure mode the transcripts exist to demonstrate. The package is already imported on line 29.

♻️ Use the contract constant
-import { formatTriggerUri } from "`@internal/dashboard-agent-contracts`";
+import { formatTriggerUri, VIEW_BLOCK_VERSION } from "`@internal/dashboard-agent-contracts`";
-  const diagnosisEnvelope = { id: `diag_${w.failedRunId}`, version: 1 };
+  const diagnosisEnvelope = { id: `diag_${w.failedRunId}`, version: VIEW_BLOCK_VERSION };
   const failuresChart = {
     id: "chart_failures_by_task",
     revision: 0,
-    version: 1,
+    version: VIEW_BLOCK_VERSION,
   const pendingChart = {
     id: "chart_pending_runs",
     revision: 0,
-    version: 1,
+    version: VIEW_BLOCK_VERSION,

Also applies to: 332-362

apps/webapp/test/seedAgentExamplesChats.test.ts (1)

176-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Read the kind with the contracts parser rather than split("/")[4].

Positional indexing silently mis-classifies if the URI layout changes — a run URI read as report would skip the resolution assertion entirely, and the test would still pass. demo.test.ts uses safeParseTriggerUri for exactly this.

♻️ Parse instead of index
     for (const uri of uris) {
-      const kind = uri.split("/")[4];
-      if (UNRESOLVABLE_KINDS.includes(kind)) continue;
+      const parsed = safeParseTriggerUri(uri);
+      expect(parsed.success, uri).toBe(true);
+      if (!parsed.success || UNRESOLVABLE_KINDS.includes(parsed.data.kind)) continue;
       const resolved = resolveTriggerUri(SCOPE, uri);

Add the import:

import { safeParseTriggerUri } from "`@internal/dashboard-agent-contracts`";
internal-packages/dashboard-agent-contracts/src/trigger-uri.ts (1)

320-341: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Duplicate line params are silently accepted, last one wins.

trigger://…/source/abc/a.ts?line=1&line=2 parses as line: 2. Everything else in the grammar rejects non-canonical input (fragments, unknown params, empty segments), so accepting a duplicate here is inconsistent and lets two different URIs mean the same resource.

♻️ Reject duplicates
   for (const [key, value] of params) {
     if (key !== "line") {
       return { success: false, error: `unknown query param "${key}"` };
     }
 
+    if (line !== undefined) {
+      return { success: false, error: "duplicate query param \"line\"" };
+    }
+
     if (!/^\d+$/.test(value) || Number(value) < 1) {
internal-packages/dashboard-agent/src/watch-tick.ts (1)

212-224: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

wakeAction infers the action type from "not fired".

If isTerminalWatchStatus ever admits a third terminal status (e.g. cancelled, which the contract's watchStatusSchema includes), the delivery-only path produces type: "watch.expired" with id: watch:<id>:cancelled — a type/id pair that doesn't describe what happened. Switching on the status explicitly keeps that from slipping through silently.

♻️ Switch on the status
 function wakeAction(watch: Watch, facts: Record<string, unknown>): WatchWakeAction {
   const spec = watch.spec as PersistedWatchSpec;
+  if (watch.status !== "fired" && watch.status !== "expired") {
+    throw new Error(`cannot build a wake for a ${watch.status} watch`);
+  }
   return {
-    type: watch.status === "fired" ? "watch.fired" : "watch.expired",
+    type: watch.status === "fired" ? "watch.fired" : "watch.expired",
internal-packages/dashboard-agent/src/dashboard-agent.eval.ts (1)

582-585: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use APICallError.isInstance(error) for provider error detection.

error.name.includes("APICallError") depends on the error name surviving any wrapping or renaming; the SDK’s provided type guard is more reliable.

♻️ Use the SDK's type guard
-      const infra = error instanceof Error && error.name.includes("APICallError");
+      const infra = APICallError.isInstance(error);

plus import { APICallError } from "ai";

internal-packages/dashboard-agent/src/dashboard-agent.test.ts (1)

429-432: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Poll the eval-enqueue side effect instead of relying on a fixed sleep.

turnAtRate waits only 30 ms before returning calls, which can still fail when the runner is loaded. Move the assertion out of the helper and make it wait for the expected call count, e.g. vi.waitFor(() => expect(calls).toHaveLength(1), { timeout: 2000 }); for the rate-0 path keep a bounded wait on “still empty” if needed.

internal-packages/dashboard-agent-contracts/src/watch.ts (1)

38-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider z.discriminatedUnion("kind", [...]) instead of z.union.

All five branches share a literal kind discriminator, so this is a textbook case for z.discriminatedUnion. With plain z.union, an invalid payload (e.g., wrong kind or a bad runId) produces a combined invalid_union error listing every failed branch, which is noisier to surface back to the agent/tool-caller than the targeted error discriminatedUnion gives.

♻️ Proposed refactor
-export const watchSpecSchema = z.union([
+export const watchSpecSchema = z.discriminatedUnion("kind", [
   watchCommonSchema
     .extend({ kind: z.literal("run_start"), runId: z.string() })
     .merge(runStateCadenceSchema),
internal-packages/dashboard-agent-db/src/queries.ts (1)

684-698: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared unread-wake predicate.

The same (last_read_at is null or coalesce(fired_at, last_checked_at) > last_read_at) clause plus the status in ('fired','expired') + tenancy join is repeated verbatim in countUnreadWatchWakes, listUnreadWatchWakes (Line 744), and listChatIdsWithUnreadWakes (Line 783). One helper returning the and(...) condition keeps the wake definition single-sourced — the doc comments already assert all three share it.

♻️ Sketch
+function unreadWakeCondition(params: { organizationId: string; userId: string }) {
+  return and(
+    inArray(watches.status, ["fired", "expired"]),
+    eq(chats.organizationId, params.organizationId),
+    eq(chats.userId, params.userId),
+    isNull(chats.deletedAt),
+    sql`(${chats.lastReadAt} is null or coalesce(${watches.firedAt}, ${watches.lastCheckedAt}) > ${chats.lastReadAt})`
+  );
+}
internal-packages/dashboard-agent/VERDICTS.md (1)

104-108: 📐 Maintainability & Code Quality | 🔵 Trivial

Track the documented queuedDuration bug.

RunPresenter.server.ts computing queuedDuration as startedAt − createdAt is recorded here as knowingly unfixed, which over-reports for delayed/scheduled runs in the dashboard. Want me to open an issue so it doesn't only live in this markdown file?

internal-packages/dashboard-agent/src/dashboard-agent.ts (1)

622-626: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use the same non-null assertion as withCacheBreakpointOnLast.

sanitized[sanitized.length - 1] is typed ModelMessage | undefined under noUncheckedIndexedAccess, and it's then spread at Line 628. The helper at Line 378 already handles this with !; mirror it here so the two paths type-check identically.

♻️ Proposed tweak
-    const last = sanitized[sanitized.length - 1];
+    const last = sanitized[sanitized.length - 1]!;
internal-packages/dashboard-agent/src/tool-schemas.ts (1)

398-403: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Validate the alert email shape in the schema.

email accepts any string, so a malformed value only fails downstream (or worse, gets persisted as a subscription address). z.string().email() makes the model's mistake a tool-validation error it can correct in-turn.

♻️ Proposed change
     email: z
-      .string()
+      .string()
+      .email()
       .optional()
       .describe("Email to alert. Omit to use the user's own account email."),
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx (1)

92-97: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

unknown[] + as never throws away the block contract.

blocksFor returns unknown[], forcing blocks as never at the ViewBlocks call site, so a block-shape change in @internal/dashboard-agent-contracts won't surface at compile time here. Typing the return as the catalog's block union would keep the boundary checked.

Also applies to: 222-228

apps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsx (1)

471-476: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

?? [] hands a new array down on every render.

chatWatches gets a fresh identity each render, which flows into DashboardAgentChatDashboardAgentMessages and defeats the memo on DashboardAgentTurn (its watches prop always compares unequal). A module-level const NO_WATCHES: WatchChip[] = [] fallback keeps the reference stable.

apps/webapp/app/components/dashboard-agent/DashboardAgentSuggestedPrompts.tsx (1)

58-65: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Name the "no page context" fallback.

The inline { page: { kind: "other", path: "" }, signals: [] } is a placeholder context built at the call site; a shared named constant (e.g. UNKNOWN_PAGE_CONTEXT in suggested-prompts/registry.ts) keeps the meaning of the empty path explicit and reusable.

As per coding guidelines: "Use named constants for sentinel or placeholder values instead of scattering raw string literals across comparisons."

Source: Coding guidelines

apps/webapp/app/components/dashboard-agent/suggested-prompts/registry.ts (1)

217-222: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

SIGNAL_PRIORITY isn't exhaustiveness-checked, and the two iterators duplicate one loop.

SIGNAL_SLOT is a Record<AgentPageSignalKind, …>, so a new signal kind fails to compile there — but SIGNAL_PRIORITY is a bare array, and since both iterators drive off it, a kind missing from the array silently never produces a chip. contextualPrompts is also contextualPromptsBySlot flattened in slot order.

♻️ Make the priority list exhaustive and derive the flat list
-export const SIGNAL_PRIORITY: AgentPageSignalKind[] = [
+// A tuple typed against the kind union: omitting a new kind is a compile error.
+export const SIGNAL_PRIORITY = [
   "fresh_failure",
   "waiting_run",
   "slow_run",
   "concurrency_saturation",
-];
+] as const satisfies readonly AgentPageSignalKind[];
 export function contextualPrompts(context: AgentPageContext, now: number): SuggestedPrompt[] {
-  const prompts: SuggestedPrompt[] = [];
-  for (const kind of SIGNAL_PRIORITY) {
-    for (const signal of context.signals) {
-      if (signal.kind !== kind) continue;
-      const prompt = promptForSignal(signal, now);
-      if (prompt) prompts.push(prompt);
-    }
-  }
-  return prompts;
+  const bySlot = contextualPromptsBySlot(context, now);
+  return PROMPT_SLOTS.flatMap((slot) => bySlot[slot]);
 }

Note: this changes contextualPrompts ordering from signal-priority to slot order — keep the current loop if callers depend on the former.

Also applies to: 284-320

apps/webapp/app/components/dashboard-agent/ReportView.tsx (1)

37-39: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Comment describes a registration side effect that doesn't exist.

healthMessages is used purely as a value in the static CATALOGS map on Line 89 — nothing self-registers on import. Worth correcting so a future reader doesn't assume adding an import is enough to register a new report's catalog.

apps/webapp/app/components/dashboard-agent/agent-badges.tsx (1)

46-46: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Hand-rolled icon component signature duplicated across two files. Both files type heroicons components as a bare call signature returning JSX.Element, which is version-sensitive (ForwardRefExoticComponent's call signature returns ReactNode) and duplicated rather than shared.

  • apps/webapp/app/components/dashboard-agent/agent-badges.tsx#L46-L46: change the exported IconComponent alias to React.ComponentType<{ className?: string }>.
  • apps/webapp/app/components/dashboard-agent/WakeBanner.tsx#L77-L82: import IconComponent from ./agent-badges and type TONE_ICON as Record<AgentTone, IconComponent> instead of restating the signature inline.
apps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.ts (1)

28-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Dismissals are permanent and the key set is never pruned.

Every dismissed id leaves a key behind forever, including operator-controlled promoted-prompt ids that rotate. Consider storing a timestamp instead of "1" so stale entries can expire (and a chip can come back after a while), or prune on read.

apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.ts (1)

192-195: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Test name contradicts its fixture.

running: 10 against a concurrencyLimit of 10 is at the limit, not "idle under its limit" — the case being covered is "at capacity with an empty queue". Renaming keeps the boundary this test pins obvious.

apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.ts (1)

164-172: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

toContain("") passes vacuously if the fixture changes kind.

Line 223 in this same file already uses the stronger pattern (throw new Error("fixture changed")); the ternary here silently degrades to an assertion that can never fail. Prefer the narrowing guard for consistency.

♻️ Proposed change
   it("sends the full prompt text, not the short label", () => {
     const [failure] = resolveSuggestedPrompts(demoPageContexts.failedRun, { now: NOW });
+    const page = demoPageContexts.failedRun.page;
+    if (page.kind !== "run") throw new Error("fixture changed");
 
     expect(failure?.label).toBe("Why did this run fail?");
-    expect(failure?.prompt).toContain(
-      demoPageContexts.failedRun.page.kind === "run" ? demoPageContexts.failedRun.page.runId : ""
-    );
+    expect(failure?.prompt).toContain(page.runId);
     expect(failure?.prompt).toContain("12m ago");
   });
internal-packages/dashboard-agent/src/tools.ts (3)

596-624: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Misplaced doc block: the renderInvestigations docs sit on canonicalizeEvidence.

Two doc comments are stacked here; the first (Lines 596-613, describing block stamping and continueId) documents renderInvestigations, which is declared at Line 706. Move it there so tooling and readers attach it correctly.


722-779: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Two investigation blocks in one view collapse into one row.

currentInvestigationId is assigned from the first block's upsert, so a second investigation block in the same render_view call revises the first rather than creating a second investigation — both blocks then carry the same id with different revisions. If the schema permits multiple investigation blocks per view, consider rejecting that up front (or scoping the id per block) rather than silently merging.


1078-1089: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Comment says "double-encode" but the code encodes once.

Line 1081 applies encodeURIComponent a single time (task/my-tasktask%2Fmy-task), which is what the route's un-escaping expects. Reword the comment. Also worth noting: unlike the neighbouring tools, this returns result.data verbatim, so any series/histogram fields in the metrics payload land straight in the model's context — consider a curateQueue in line with curateReport.

apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.ts (1)

27-37: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Parse the git JSON blob with zod instead of a bare cast.

deployment.git is untyped Prisma JSON; the cast asserts a shape that is never checked, so a legacy/oddly-shaped blob would flow straight into the API response (e.g. pullRequestNumber as a string). A small z.object({...}).partial().safeParse() keeps the response contract honest.

As per coding guidelines: "Use zod for validation in packages/core and apps/webapp".

♻️ Proposed refactor
-type GitMetaBlob = {
-  source?: string;
-  commitAuthorName?: string;
-  commitMessage?: string;
-  commitRef?: string;
-  remoteUrl?: string;
-  ghUsername?: string;
-  pullRequestNumber?: number;
-  pullRequestTitle?: string;
-  pullRequestState?: string;
-};
+const GitMetaBlob = z
+  .object({
+    source: z.string(),
+    commitAuthorName: z.string(),
+    commitMessage: z.string(),
+    commitRef: z.string(),
+    remoteUrl: z.string(),
+    ghUsername: z.string(),
+    pullRequestNumber: z.number(),
+    pullRequestTitle: z.string(),
+    pullRequestState: z.string(),
+  })
+  .partial();
-    const git = (deployment?.git ?? undefined) as GitMetaBlob | undefined;
+    const parsedGit = deployment?.git ? GitMetaBlob.safeParse(deployment.git) : undefined;
+    const git = parsedGit?.success ? parsedGit.data : undefined;

Also applies to: 73-73

Source: Coding guidelines

apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts (1)

156-159: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Map ServiceValidationError from CreateAlertChannelService.call to a 4xx response.

The catch block currently treats all CreateAlertChannelService.call failures as 500, including user-input validation failures such as alert-channel limits. Distinguish ServiceValidationError here and return a 4xx, so the agent can explain the fixable failure instead of seeing an internal error.

apps/webapp/test/dashboardAgentRoutes.test.ts (1)

26-29: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Dead mock. vi.mock("~/env.server") just re-exports the original module, so it has no effect — either drop it or note why the module factory is needed (e.g. to force ESM interop ordering).

apps/webapp/test/dashboardAgentWatchToken.test.ts (1)

15-15: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Hardcoded UAT prefix can drift. WATCH_TOKEN_PREFIX is imported but tr_uat_ is literal; if the rbac package ever changes its prefix, the "disguised" tokens in the cross-rejection tests stop testing what they claim while still passing. Export/import the constant from @trigger.dev/rbac if available.

apps/webapp/test/dashboardAgentWatches.test.ts (1)

371-375: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Conditional assertion can pass vacuously. If second.ok were unexpectedly true the existingId check is skipped silently. Narrow with an early if (second.ok || !first.ok) throw new Error(...) (or expect.fail) before asserting.

apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts (1)

411-417: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Guard the cast before reading .code. Both predicates dereference an unknown value; a thrown null/undefined (or a primitive) turns the catch block itself into a TypeError, losing the original failure. A typeof error === "object" && error !== null prefix makes them safe.

🛡️ Proposed guard
 function isWebAPIPlatformError(error: unknown): error is WebAPIPlatformError {
-  return (error as WebAPIPlatformError).code === ErrorCode.PlatformError;
+  return (
+    typeof error === "object" &&
+    error !== null &&
+    (error as WebAPIPlatformError).code === ErrorCode.PlatformError
+  );
 }
 
 function isWebAPIRateLimitedError(error: unknown): error is WebAPIRateLimitedError {
-  return (error as WebAPIRateLimitedError).code === ErrorCode.RateLimitedError;
+  return (
+    typeof error === "object" &&
+    error !== null &&
+    (error as WebAPIRateLimitedError).code === ErrorCode.RateLimitedError
+  );
 }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 32f81d27-7b23-4a54-8b29-c8916991756f

📥 Commits

Reviewing files that changed from the base of the PR and between 6e5f0f0 and 0dece13.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (209)
  • .server-changes/dashboard-agent-first-turn-error.md
  • .server-changes/dashboard-agent-investigate.md
  • .server-changes/dashboard-agent-watch-alerts.md
  • .server-changes/dashboard-agent-watches.md
  • .server-changes/queue-metrics-api.md
  • .server-changes/remove-header-docs-buttons.md
  • apps/webapp/.gitignore
  • apps/webapp/app/components/dashboard-agent/AgentChart.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgent.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentChat.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentComposer.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentContextBanner.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentDraft.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentHeader.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentHistory.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentSuggestedPrompts.tsx
  • apps/webapp/app/components/dashboard-agent/InvestigateButton.tsx
  • apps/webapp/app/components/dashboard-agent/InvestigationCard.test.ts
  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/ReportView.test.ts
  • apps/webapp/app/components/dashboard-agent/ReportView.tsx
  • apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx
  • apps/webapp/app/components/dashboard-agent/WakeBanner.tsx
  • apps/webapp/app/components/dashboard-agent/WatchChips.tsx
  • apps/webapp/app/components/dashboard-agent/WatchWakeToast.tsx
  • apps/webapp/app/components/dashboard-agent/agent-badges.tsx
  • apps/webapp/app/components/dashboard-agent/chat-layout.test.ts
  • apps/webapp/app/components/dashboard-agent/chat-layout.tsx
  • apps/webapp/app/components/dashboard-agent/dashboardAgentLauncher.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoIntentBubble.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoInvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoReportCard.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoSuggestedPromptsRow.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoWatchChips.tsx
  • apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts
  • apps/webapp/app/components/dashboard-agent/demo/demo.test.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/blocks.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/chart.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/index.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/intents.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/investigation.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/messages.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/page-context.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/reports.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/watches.ts
  • apps/webapp/app/components/dashboard-agent/demo/ids.ts
  • apps/webapp/app/components/dashboard-agent/demo/index.ts
  • apps/webapp/app/components/dashboard-agent/investigate-prompts.test.ts
  • apps/webapp/app/components/dashboard-agent/investigate-prompts.ts
  • apps/webapp/app/components/dashboard-agent/list-row.tsx
  • apps/webapp/app/components/dashboard-agent/message-order.test.ts
  • apps/webapp/app/components/dashboard-agent/message-order.ts
  • apps/webapp/app/components/dashboard-agent/navigate-target.test.ts
  • apps/webapp/app/components/dashboard-agent/navigate-target.ts
  • apps/webapp/app/components/dashboard-agent/page-context-types.ts
  • apps/webapp/app/components/dashboard-agent/page-label.test.ts
  • apps/webapp/app/components/dashboard-agent/page-label.ts
  • apps/webapp/app/components/dashboard-agent/progress-line.test.ts
  • apps/webapp/app/components/dashboard-agent/progress-line.ts
  • apps/webapp/app/components/dashboard-agent/report-block-adapter.test.ts
  • apps/webapp/app/components/dashboard-agent/report-block-adapter.ts
  • apps/webapp/app/components/dashboard-agent/report-sparkline.tsx
  • apps/webapp/app/components/dashboard-agent/run-id.test.ts
  • apps/webapp/app/components/dashboard-agent/run-id.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/index.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.test.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promotedPrompt.server.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/registry.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.ts
  • apps/webapp/app/components/dashboard-agent/tool-labels.test.ts
  • apps/webapp/app/components/dashboard-agent/tool-labels.ts
  • apps/webapp/app/components/dashboard-agent/useTranscriptAutoScroll.ts
  • apps/webapp/app/components/dashboard-agent/view-blocks.test.ts
  • apps/webapp/app/components/dashboard-agent/view-blocks.ts
  • apps/webapp/app/components/dashboard-agent/view-catalog.tsx
  • apps/webapp/app/components/dashboard-agent/watch-chips.test.ts
  • apps/webapp/app/components/dashboard-agent/watch-chips.ts
  • apps/webapp/app/components/metrics/MiniLineChart.tsx
  • apps/webapp/app/components/primitives/Callout.tsx
  • apps/webapp/app/components/runs/v3/agent/AgentMessageView.tsx
  • apps/webapp/app/hooks/useAgentPageContext.ts
  • apps/webapp/app/presenters/v3/ApiAlertChannelPresenter.server.ts
  • apps/webapp/app/presenters/v3/reports/health/health-messages.ts
  • apps/webapp/app/presenters/v3/reports/health/health.ts
  • apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.server.ts
  • apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.agents.$agentParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts.new/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.apikeys/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.batches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.deployments/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.errors.$fingerprint/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.limits/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.prompts._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions.$sessionParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.test/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.waitpoints.tokens/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections.new/route.tsx
  • apps/webapp/app/routes/account.tokens/route.tsx
  • apps/webapp/app/routes/api.v1.dashboard-agent.alerts.$channelId.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.fired.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.jwt.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.repo.snapshot.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.waiting.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.workers.$tagName.ts
  • apps/webapp/app/routes/api.v1.queues.$queueParam.metrics.ts
  • apps/webapp/app/routes/resources.dashboard-agent.alerts.$channelId.unsubscribe.tsx
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.in.$.ts
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.ts
  • apps/webapp/app/routes/storybook.agent-ui/manifest.ts
  • apps/webapp/app/routes/storybook.agent-ui/route.tsx
  • apps/webapp/app/routes/storybook.callout/route.tsx
  • apps/webapp/app/services/dashboardAgentAlertContext.server.ts
  • apps/webapp/app/services/dashboardAgentAlertUnsubscribeToken.server.ts
  • apps/webapp/app/services/dashboardAgentHeadStart.server.ts
  • apps/webapp/app/services/dashboardAgentWatchAlerts.server.ts
  • apps/webapp/app/services/dashboardAgentWatchChecks.server.ts
  • apps/webapp/app/services/dashboardAgentWatchChecks.ts
  • apps/webapp/app/services/dashboardAgentWatchToken.server.ts
  • apps/webapp/app/services/dashboardAgentWatches.server.ts
  • apps/webapp/app/services/resolveTriggerUri.server.ts
  • apps/webapp/app/services/uatRoutePreamble.server.ts
  • apps/webapp/app/utils/handle.ts
  • apps/webapp/app/v3/alertsWorker.server.ts
  • apps/webapp/app/v3/featureFlags.ts
  • apps/webapp/app/v3/services/alerts/deliverAlert.server.ts
  • apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts
  • apps/webapp/package.json
  • apps/webapp/scripts/agent-ui-screenshots.ts
  • apps/webapp/seed-agent-examples-chats.mts
  • apps/webapp/seed-agent-examples.mts
  • apps/webapp/seed-queue-metrics.mts
  • apps/webapp/test/dashboardAgentHeadStart.test.ts
  • apps/webapp/test/dashboardAgentRoutes.test.ts
  • apps/webapp/test/dashboardAgentWatchChecks.test.ts
  • apps/webapp/test/dashboardAgentWatchToken.test.ts
  • apps/webapp/test/dashboardAgentWatches.test.ts
  • apps/webapp/test/reportHealth.test.ts
  • apps/webapp/test/resolveTriggerUri.test.ts
  • apps/webapp/test/seedAgentExamplesChats.test.ts
  • apps/webapp/test/waitingRunDiagnosis.test.ts
  • apps/webapp/vitest.config.ts
  • internal-packages/dashboard-agent-contracts/package.json
  • internal-packages/dashboard-agent-contracts/src/blocks.test.ts
  • internal-packages/dashboard-agent-contracts/src/blocks.ts
  • internal-packages/dashboard-agent-contracts/src/contracts.test.ts
  • internal-packages/dashboard-agent-contracts/src/evidence.ts
  • internal-packages/dashboard-agent-contracts/src/index.ts
  • internal-packages/dashboard-agent-contracts/src/intent.ts
  • internal-packages/dashboard-agent-contracts/src/page-context.ts
  • internal-packages/dashboard-agent-contracts/src/run-filters.ts
  • internal-packages/dashboard-agent-contracts/src/suggested-prompts.ts
  • internal-packages/dashboard-agent-contracts/src/trigger-uri.test.ts
  • internal-packages/dashboard-agent-contracts/src/trigger-uri.ts
  • internal-packages/dashboard-agent-contracts/src/watch.test.ts
  • internal-packages/dashboard-agent-contracts/src/watch.ts
  • internal-packages/dashboard-agent-contracts/tsconfig.json
  • internal-packages/dashboard-agent-contracts/vitest.config.ts
  • internal-packages/dashboard-agent-db/README.md
  • internal-packages/dashboard-agent-db/drizzle/0002_luxuriant_king_cobra.sql
  • internal-packages/dashboard-agent-db/drizzle/0003_famous_champions.sql
  • internal-packages/dashboard-agent-db/drizzle/meta/0002_snapshot.json
  • internal-packages/dashboard-agent-db/drizzle/meta/0003_snapshot.json
  • internal-packages/dashboard-agent-db/drizzle/meta/_journal.json
  • internal-packages/dashboard-agent-db/package.json
  • internal-packages/dashboard-agent-db/src/ids.ts
  • internal-packages/dashboard-agent-db/src/index.ts
  • internal-packages/dashboard-agent-db/src/queries.ts
  • internal-packages/dashboard-agent-db/src/schema.ts
  • internal-packages/dashboard-agent/GUIDEBOOK.md
  • internal-packages/dashboard-agent/PLAYBOOK.md
  • internal-packages/dashboard-agent/VERDICTS.md
  • internal-packages/dashboard-agent/package.json
  • internal-packages/dashboard-agent/src/dashboard-agent.eval.ts
  • internal-packages/dashboard-agent/src/dashboard-agent.test.ts
  • internal-packages/dashboard-agent/src/dashboard-agent.ts
  • internal-packages/dashboard-agent/src/index.ts
  • internal-packages/dashboard-agent/src/tool-schemas.ts
  • internal-packages/dashboard-agent/src/tools.ts
  • internal-packages/dashboard-agent/src/watch-tick.test.ts
  • internal-packages/dashboard-agent/src/watch-tick.ts
  • internal-packages/dashboard-agent/vitest.eval.config.ts
  • internal-packages/database/prisma/migrations/20260729120000_add_dashboard_agent_watch_alert_type/migration.sql
  • internal-packages/database/prisma/schema.prisma
  • internal-packages/emails/emails/alert-dashboard-agent-watch.tsx
  • internal-packages/emails/src/index.tsx
💤 Files with no reviewable changes (1)
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx

Comment on lines +76 to +80
<SimpleTooltip
side="bottom"
content={watchChipTooltip(watch)}
button={<span className="max-w-[12rem] truncate">{label}</span>}
/>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

The note/cadence tooltip is mouse-only.

The chip's trigger is a plain <span>, so keyboard and screen-reader users never reach the tooltip — and per the comment on Lines 70-72 the native title was deliberately dropped, making this the only path to the note and cadence. SimpleTooltip already supports tabbable (used for the cancel button on Line 84); apply it here too.

♿ Proposed fix
             <SimpleTooltip
+              tabbable
               side="bottom"
               content={watchChipTooltip(watch)}
               button={<span className="max-w-[12rem] truncate">{label}</span>}
             />
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<SimpleTooltip
side="bottom"
content={watchChipTooltip(watch)}
button={<span className="max-w-[12rem] truncate">{label}</span>}
/>
<SimpleTooltip
tabbable
side="bottom"
content={watchChipTooltip(watch)}
button={<span className="max-w-[12rem] truncate">{label}</span>}
/>

Comment on lines +110 to +122
export function showWatchWakesSummaryToast(count: number, onOpenChat: () => void) {
show(
(t) => (
<WakeToastUI
t={t}
title="Watch updates"
message={`${count} watch updates — open the chat panel.`}
onOpenChat={onOpenChat}
/>
),
`watch-wakes-summary-${count}-${Date.now()}`
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Date.now() in the toast id defeats the de-duplication this helper exists for.

Every call produces a unique id, so a repeated poll stacks another summary toast — and these never auto-dismiss (duration: Infinity), so they accumulate until the user clears each one. Use a stable id for the summary toast; sonner will update the existing one when the count changes.

🐛 Proposed fix
-    `watch-wakes-summary-${count}-${Date.now()}`
+    "watch-wakes-summary"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function showWatchWakesSummaryToast(count: number, onOpenChat: () => void) {
show(
(t) => (
<WakeToastUI
t={t}
title="Watch updates"
message={`${count} watch updates — open the chat panel.`}
onOpenChat={onOpenChat}
/>
),
`watch-wakes-summary-${count}-${Date.now()}`
);
}
export function showWatchWakesSummaryToast(count: number, onOpenChat: () => void) {
show(
(t) => (
<WakeToastUI
t={t}
title="Watch updates"
message={`${count} watch updates — open the chat panel.`}
onOpenChat={onOpenChat}
/>
),
"watch-wakes-summary"
);
}

Comment on lines +330 to +399
function deriveCause(
queue: WaitingRunDiagnosis["queue"],
signals: WaitingRunQueueSignals | null
): { cause: WaitingRunCause; evidence: WaitingRunDiagnosis["diagnosis"]["evidence"] } {
const t = HEALTH_THRESHOLDS.flowCause;

if (!signals || queue.sampleBuckets === 0) {
return {
cause: "unknown",
evidence: {
backlogGrowing: false,
throttledShare: queue.throttled.share,
envRunningShare: null,
missing: "queue_signals",
},
};
}

const backlogGrowing = isPendingIncreasing(signals.depthSeries);
const throttledShare = queue.throttled.share;
// Same guard as flow.ts #1: without a real limit AND a real running reading, a share is a
// meaningless 0 that would falsely select `stall`.
const hasConcurrencyEvidence =
signals.envLimit !== null && signals.envLimit > 0 && signals.envRunning !== null;
const envRunningShare = hasConcurrencyEvidence
? (signals.envRunning as number) / (signals.envLimit as number)
: null;
const envPinned = envRunningShare !== null && envRunningShare >= t.pinnedLevel;
// A queue's own limit is visible through throttling: `throttled_count` counts exactly the
// emissions where running >= limit while work was queued. Sustained (most of the window)
// reads as pinned at the queue limit; intermittent reads as throttled.
const queueLimitPinned = throttledShare >= t.pinnedShare;
const queueThrottled = throttledShare >= t.throttledShare;
const backlogged = queue.depth !== null && queue.depth > 0;
const observedRate = queue.observedThroughputPerMin;

const evidence = {
backlogGrowing,
throttledShare,
envRunningShare,
missing: null as WaitingRunDiagnosis["diagnosis"]["evidence"]["missing"],
};

// Priority order copied from flow.ts: stall is a last-resort "it's on our side" cause, so a
// known config bottleneck (queue throttling) must rule it out first.
if (
hasConcurrencyEvidence &&
!queueThrottled &&
(envRunningShare as number) < t.stallRunningShare &&
backlogged &&
observedRate === 0
) {
return { cause: "stall", evidence };
}
if (envPinned && backlogged) {
return { cause: "env_limit_pinned", evidence };
}
if (queueLimitPinned && backlogged) {
return { cause: "queue_limit_pinned", evidence };
}
if (queueThrottled && backlogged) {
return { cause: "throttled", evidence };
}
if (!backlogged || (observedRate !== null && observedRate > 0)) {
return { cause: "draining_normally", evidence };
}
// Backlogged with nothing moving, but no capacity evidence to say whether that's a limit or a
// stall. flow.ts's lesson: don't name a concurrency cause without the evidence for it.
return { cause: "unknown", evidence: { ...evidence, missing: "env_concurrency" } };
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

missing: "env_concurrency" fallback mislabels evidence that's actually present.

The final fallback (Line 398) unconditionally reports missing: "env_concurrency", but this branch is reachable even when hasConcurrencyEvidence is true (e.g. envRunningShare between the stall and pinned thresholds, or observedRate unmeasured rather than exactly 0 — the stall check requires observedRate === 0, so a null rate never satisfies it). In those cases concurrency data isn't missing at all; the diagnosis is just inconclusive, but a consumer reading evidence.missing will be told the wrong thing is absent. This directly undercuts the module's own "never overclaim" design intent stated in the file header.

🐛 Proposed fix
   // Backlogged with nothing moving, but no capacity evidence to say whether that's a limit or a
   // stall. flow.ts's lesson: don't name a concurrency cause without the evidence for it.
-  return { cause: "unknown", evidence: { ...evidence, missing: "env_concurrency" } };
+  return {
+    cause: "unknown",
+    evidence: { ...evidence, missing: hasConcurrencyEvidence ? null : "env_concurrency" },
+  };

Consider adding a test where envRunning/envLimit are both present but the share falls between the stall and pinned thresholds (or startedCount: null) with a non-zero backlog, to lock in the correct missing value going forward.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function deriveCause(
queue: WaitingRunDiagnosis["queue"],
signals: WaitingRunQueueSignals | null
): { cause: WaitingRunCause; evidence: WaitingRunDiagnosis["diagnosis"]["evidence"] } {
const t = HEALTH_THRESHOLDS.flowCause;
if (!signals || queue.sampleBuckets === 0) {
return {
cause: "unknown",
evidence: {
backlogGrowing: false,
throttledShare: queue.throttled.share,
envRunningShare: null,
missing: "queue_signals",
},
};
}
const backlogGrowing = isPendingIncreasing(signals.depthSeries);
const throttledShare = queue.throttled.share;
// Same guard as flow.ts #1: without a real limit AND a real running reading, a share is a
// meaningless 0 that would falsely select `stall`.
const hasConcurrencyEvidence =
signals.envLimit !== null && signals.envLimit > 0 && signals.envRunning !== null;
const envRunningShare = hasConcurrencyEvidence
? (signals.envRunning as number) / (signals.envLimit as number)
: null;
const envPinned = envRunningShare !== null && envRunningShare >= t.pinnedLevel;
// A queue's own limit is visible through throttling: `throttled_count` counts exactly the
// emissions where running >= limit while work was queued. Sustained (most of the window)
// reads as pinned at the queue limit; intermittent reads as throttled.
const queueLimitPinned = throttledShare >= t.pinnedShare;
const queueThrottled = throttledShare >= t.throttledShare;
const backlogged = queue.depth !== null && queue.depth > 0;
const observedRate = queue.observedThroughputPerMin;
const evidence = {
backlogGrowing,
throttledShare,
envRunningShare,
missing: null as WaitingRunDiagnosis["diagnosis"]["evidence"]["missing"],
};
// Priority order copied from flow.ts: stall is a last-resort "it's on our side" cause, so a
// known config bottleneck (queue throttling) must rule it out first.
if (
hasConcurrencyEvidence &&
!queueThrottled &&
(envRunningShare as number) < t.stallRunningShare &&
backlogged &&
observedRate === 0
) {
return { cause: "stall", evidence };
}
if (envPinned && backlogged) {
return { cause: "env_limit_pinned", evidence };
}
if (queueLimitPinned && backlogged) {
return { cause: "queue_limit_pinned", evidence };
}
if (queueThrottled && backlogged) {
return { cause: "throttled", evidence };
}
if (!backlogged || (observedRate !== null && observedRate > 0)) {
return { cause: "draining_normally", evidence };
}
// Backlogged with nothing moving, but no capacity evidence to say whether that's a limit or a
// stall. flow.ts's lesson: don't name a concurrency cause without the evidence for it.
return { cause: "unknown", evidence: { ...evidence, missing: "env_concurrency" } };
}
function deriveCause(
queue: WaitingRunDiagnosis["queue"],
signals: WaitingRunQueueSignals | null
): { cause: WaitingRunCause; evidence: WaitingRunDiagnosis["diagnosis"]["evidence"] } {
const t = HEALTH_THRESHOLDS.flowCause;
if (!signals || queue.sampleBuckets === 0) {
return {
cause: "unknown",
evidence: {
backlogGrowing: false,
throttledShare: queue.throttled.share,
envRunningShare: null,
missing: "queue_signals",
},
};
}
const backlogGrowing = isPendingIncreasing(signals.depthSeries);
const throttledShare = queue.throttled.share;
// Same guard as flow.ts `#1`: without a real limit AND a real running reading, a share is a
// meaningless 0 that would falsely select `stall`.
const hasConcurrencyEvidence =
signals.envLimit !== null && signals.envLimit > 0 && signals.envRunning !== null;
const envRunningShare = hasConcurrencyEvidence
? (signals.envRunning as number) / (signals.envLimit as number)
: null;
const envPinned = envRunningShare !== null && envRunningShare >= t.pinnedLevel;
// A queue's own limit is visible through throttling: `throttled_count` counts exactly the
// emissions where running >= limit while work was queued. Sustained (most of the window)
// reads as pinned at the queue limit; intermittent reads as throttled.
const queueLimitPinned = throttledShare >= t.pinnedShare;
const queueThrottled = throttledShare >= t.throttledShare;
const backlogged = queue.depth !== null && queue.depth > 0;
const observedRate = queue.observedThroughputPerMin;
const evidence = {
backlogGrowing,
throttledShare,
envRunningShare,
missing: null as WaitingRunDiagnosis["diagnosis"]["evidence"]["missing"],
};
// Priority order copied from flow.ts: stall is a last-resort "it's on our side" cause, so a
// known config bottleneck (queue throttling) must rule it out first.
if (
hasConcurrencyEvidence &&
!queueThrottled &&
(envRunningShare as number) < t.stallRunningShare &&
backlogged &&
observedRate === 0
) {
return { cause: "stall", evidence };
}
if (envPinned && backlogged) {
return { cause: "env_limit_pinned", evidence };
}
if (queueLimitPinned && backlogged) {
return { cause: "queue_limit_pinned", evidence };
}
if (queueThrottled && backlogged) {
return { cause: "throttled", evidence };
}
if (!backlogged || (observedRate !== null && observedRate > 0)) {
return { cause: "draining_normally", evidence };
}
// Backlogged with nothing moving, but no capacity evidence to say whether that's a limit or a
// stall. flow.ts's lesson: don't name a concurrency cause without the evidence for it.
return {
cause: "unknown",
evidence: { ...evidence, missing: hasConcurrencyEvidence ? null : "env_concurrency" },
};
}

Comment on lines +132 to +153
// Default to the account email: the agent must not be able to point an alert at
// an address the user didn't give it.
let email = body.email;
if (!email) {
const user = await $replica.user.findFirst({ where: { id: userId }, select: { email: true } });
if (!user) {
return json({ error: "User not found", code: "invalid_request" }, { status: 404 });
}
email = user.email;
}

try {
const service = new CreateAlertChannelService();
const channel = await service.call(environment.project.externalRef, userId, {
name: `Watch alerts for ${email}`,
alertTypes: [DASHBOARD_AGENT_WATCH_ALERT_TYPE],
environmentTypes: [environment.type],
// Stable per (email, project): asking twice re-enables the existing
// subscription instead of stacking duplicate channels.
deduplicationKey: `dashboard-agent-watch:${email}`,
channel: { type: "EMAIL", email },
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Any caller-supplied email is accepted, contradicting the stated intent.

The comment says the agent must not be able to point an alert at an address the user didn't give it, but body.email (Line 40) is only validated as a well-formed address — it isn't checked against the authenticated user's own email or org membership. A delegated agent token (or a prompt-injected agent) can therefore subscribe an arbitrary third-party address to this project's watch alerts, leaking watch details and creating a mail-sending vector. Also normalize the address before using it in deduplicationKey, otherwise User@x.com and user@x.com create two channels for the same mailbox.

🛡️ Proposed fix: restrict to the account email (or an org member's), and normalize
-  let email = body.email;
-  if (!email) {
-    const user = await $replica.user.findFirst({ where: { id: userId }, select: { email: true } });
-    if (!user) {
-      return json({ error: "User not found", code: "invalid_request" }, { status: 404 });
-    }
-    email = user.email;
-  }
+  const user = await $replica.user.findFirst({ where: { id: userId }, select: { email: true } });
+  if (!user) {
+    return json({ error: "User not found", code: "invalid_request" }, { status: 404 });
+  }
+  const accountEmail = user.email.trim().toLowerCase();
+  const requested = body.email?.trim().toLowerCase();
+  if (requested && requested !== accountEmail) {
+    return json(
+      { error: "Alerts can only be sent to your account email", code: "invalid_request" },
+      { status: 403 }
+    );
+  }
+  const email = accountEmail;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Default to the account email: the agent must not be able to point an alert at
// an address the user didn't give it.
let email = body.email;
if (!email) {
const user = await $replica.user.findFirst({ where: { id: userId }, select: { email: true } });
if (!user) {
return json({ error: "User not found", code: "invalid_request" }, { status: 404 });
}
email = user.email;
}
try {
const service = new CreateAlertChannelService();
const channel = await service.call(environment.project.externalRef, userId, {
name: `Watch alerts for ${email}`,
alertTypes: [DASHBOARD_AGENT_WATCH_ALERT_TYPE],
environmentTypes: [environment.type],
// Stable per (email, project): asking twice re-enables the existing
// subscription instead of stacking duplicate channels.
deduplicationKey: `dashboard-agent-watch:${email}`,
channel: { type: "EMAIL", email },
});
// Default to the account email: the agent must not be able to point an alert at
// an address the user didn't give it.
const user = await $replica.user.findFirst({ where: { id: userId }, select: { email: true } });
if (!user) {
return json({ error: "User not found", code: "invalid_request" }, { status: 404 });
}
const accountEmail = user.email.trim().toLowerCase();
const requested = body.email?.trim().toLowerCase();
if (requested && requested !== accountEmail) {
return json(
{ error: "Alerts can only be sent to your account email", code: "invalid_request" },
{ status: 403 }
);
}
const email = accountEmail;
try {
const service = new CreateAlertChannelService();
const channel = await service.call(environment.project.externalRef, userId, {
name: `Watch alerts for ${email}`,
alertTypes: [DASHBOARD_AGENT_WATCH_ALERT_TYPE],
environmentTypes: [environment.type],
// Stable per (email, project): asking twice re-enables the existing
// subscription instead of stacking duplicate channels.
deduplicationKey: `dashboard-agent-watch:${email}`,
channel: { type: "EMAIL", email },
});

Comment on lines +78 to +148
export async function authorizeWatchEnvironment(params: {
userId: string;
organizationId: string;
projectId: string;
environmentId: string;
}): Promise<WatchAuthorization> {
const environment = await $replica.runtimeEnvironment.findFirst({
where: {
id: params.environmentId,
// The watch's snapshot has to still describe this environment — a mismatch
// means the row is being used to reach somewhere it was never created for.
projectId: params.projectId,
organizationId: params.organizationId,
archivedAt: null,
project: { deletedAt: null },
organization: { deletedAt: null, members: { some: { userId: params.userId } } },
OR: [
{ type: { in: ["PREVIEW", "STAGING", "PRODUCTION"] } },
// Dev environments are per-member: only their owner may read them.
{ type: "DEVELOPMENT", orgMember: { userId: params.userId } },
],
},
include: authIncludeWithParent,
});

if (!environment) return { ok: false, reason: "access_revoked" };

const user = await $replica.user.findFirst({
where: { id: params.userId },
select: { admin: true },
});
if (!user) return { ok: false, reason: "access_revoked" };

const allowed = await canAccessDashboardAgent({
userId: params.userId,
isAdmin: user.admin,
// A background check is never an impersonated session.
isImpersonating: false,
organizationSlug: environment.organization.slug,
orgFeatureFlags: environment.organization.featureFlags as Record<string, unknown> | null,
});
if (!allowed) return { ok: false, reason: "access_revoked" };

return { ok: true, environment: toAuthenticated(environment) };
}

/**
* The same authorization, addressed by environment id alone — for the creation
* path, where no watch row (and so no org/project snapshot to cross-check) exists
* yet. The id lookup is unscoped on purpose and proves nothing; every membership,
* dev-owner and feature-gate rule is applied by `authorizeWatchEnvironment` below
* it, so an id the user can't reach still resolves to `null`.
*/
export async function authorizeWatchEnvironmentById(params: {
userId: string;
environmentId: string;
}): Promise<AuthenticatedEnvironment | null> {
const environment = await $replica.runtimeEnvironment.findFirst({
where: { id: params.environmentId },
select: { organizationId: true, projectId: true },
});
if (!environment) return null;

const authorization = await authorizeWatchEnvironment({
userId: params.userId,
organizationId: environment.organizationId,
projectId: environment.projectId,
environmentId: params.environmentId,
});
return authorization.ok ? authorization.environment : null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate file =="
fd -a 'dashboardAgentWatches\.server\.ts$' . || true

echo "== file outline =="
file="$(fd 'dashboardAgentWatches\.server\.ts$' . | head -n1 || true)"
if [ -n "${file:-}" ]; then
  wc -l "$file"
  ast-grep outline "$file" || true
  echo "== relevant lines 1-180 =="
  sed -n '1,180p' "$file" | nl -ba
fi

echo "== search authorization / replica usage in file =="
if [ -n "${file:-}" ]; then
  rg -n '\$replica|authorizeWatchEnvironment|authorizeWatchEnvironmentById|runtimeEnvironment|canAccessDashboardAgent|findFirst|findUnique' "$file" || true
fi

echo "== db client definitions for replica/prisma =="
rg -n '\b\$replica\b|\bexport const prisma\b|\bexport const .*prisma\b|\bnew PrismaClient\b' . --glob '!node_modules' --glob '!dist' --glob '!build' | head -n 200

Repository: triggerdotdev/trigger.dev

Length of output: 2044


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== repository root files =="
git ls-files apps/webapp/app/services/dashboardAgentWatches.server.ts || true

echo "== locate file =="
fd 'dashboardAgentWatches\.server\.ts$' . || true

echo "== file outline =="
file="$(fd 'dashboardAgentWatches\.server\.ts$' . | head -n1 || true)"
if [ -n "${file:-}" ]; then
  wc -l "$file"
  ast-grep outline "$file" || true
  echo "== relevant lines 1-180 =="
  sed -n '1,180p' "$file" | nl -ba
fi

echo "== search authorization / replica usage in file =="
if [ -n "${file:-}" ]; then
  rg -n '\$replica|authorizeWatchEnvironment|authorizeWatchEnvironmentById|runtimeEnvironment|canAccessDashboardAgent|findFirst|findUnique' "$file" || true
fi

echo "== db client definitions for replica/prisma =="
rg -n '\b\$replica\b|\bexport const prisma\b|\bexport const .*prisma\b|\bnew PrismaClient\b' . --glob '!node_modules' --glob '!dist' --glob '!build' | head -n 200

Repository: triggerdotdev/trigger.dev

Length of output: 2044


Run watch re-authorization against the primary Prisma client.

authorizeWatchEnvironment is the per-tick gate for runtimeEnvironment, org membership, dev-environment ownership, project deletion, and user/admin status. Reading these revocation-sensitive rows from $replica can allow a just-revoked user to pass while the replica is lagging, letting one more tick fire/deliver an alert on data they should no longer access. At minimum, use the primary client for the authorization-scoped runtimeEnvironment.findFirst and user.findFirst.

Source: Learnings

await import("~/routes/api.v1.dashboard-agent.watches.$watchId.check");
const { action: createAction } = await import("~/routes/api.v1.dashboard-agent.watches");
const { signDashboardAgentWatchToken } = await import("~/services/dashboardAgentWatchToken.server");
const { env } = await import("~/env.server");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Don't import env.server from a webapp test. env.SESSION_SECRET is only needed by tokenFor; pass the secret in as a parameter/constant instead so the test doesn't drag the env schema (and its required-var validation) into the suite.

As per coding guidelines: "Test files must not import app/env.server.ts; pass configuration as options instead."

Source: Coding guidelines

Comment on lines +87 to +103
const AGENT_MIGRATIONS = [
"0000_magenta_lilandra",
"0001_slimy_living_tribunal",
"0002_luxuriant_king_cobra",
];

/** Apply the dashboard-agent schema by replaying its Drizzle migration SQL. */
async function applyAgentSchema(prisma: PrismaClient) {
const folder = path.resolve(__dirname, "../../../internal-packages/dashboard-agent-db/drizzle");
for (const name of AGENT_MIGRATIONS) {
const sql = readFileSync(path.join(folder, `${name}.sql`), "utf8");
for (const statement of sql.split("--> statement-breakpoint")) {
const trimmed = statement.trim();
if (trimmed.length > 0) await prisma.$executeRawUnsafe(trimmed);
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Hardcoded migration list will rot. This PR also adds internal-packages/dashboard-agent-db/drizzle/0003_famous_champions.sql, which this array omits — so the container schema silently lags the real one and any query touching the newer columns (e.g. chat read tracking) will fail or be untested. Read the migration set from drizzle/meta/_journal.json (or glob *.sql sorted) instead of listing names.

♻️ Derive the list from the journal
-const AGENT_MIGRATIONS = [
-  "0000_magenta_lilandra",
-  "0001_slimy_living_tribunal",
-  "0002_luxuriant_king_cobra",
-];
-
 /** Apply the dashboard-agent schema by replaying its Drizzle migration SQL. */
 async function applyAgentSchema(prisma: PrismaClient) {
   const folder = path.resolve(__dirname, "../../../internal-packages/dashboard-agent-db/drizzle");
-  for (const name of AGENT_MIGRATIONS) {
+  const journal = JSON.parse(readFileSync(path.join(folder, "meta/_journal.json"), "utf8")) as {
+    entries: Array<{ tag: string }>;
+  };
+  for (const { tag: name } of journal.entries) {
     const sql = readFileSync(path.join(folder, `${name}.sql`), "utf8");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const AGENT_MIGRATIONS = [
"0000_magenta_lilandra",
"0001_slimy_living_tribunal",
"0002_luxuriant_king_cobra",
];
/** Apply the dashboard-agent schema by replaying its Drizzle migration SQL. */
async function applyAgentSchema(prisma: PrismaClient) {
const folder = path.resolve(__dirname, "../../../internal-packages/dashboard-agent-db/drizzle");
for (const name of AGENT_MIGRATIONS) {
const sql = readFileSync(path.join(folder, `${name}.sql`), "utf8");
for (const statement of sql.split("--> statement-breakpoint")) {
const trimmed = statement.trim();
if (trimmed.length > 0) await prisma.$executeRawUnsafe(trimmed);
}
}
}
/** Apply the dashboard-agent schema by replaying its Drizzle migration SQL. */
async function applyAgentSchema(prisma: PrismaClient) {
const folder = path.resolve(__dirname, "../../../internal-packages/dashboard-agent-db/drizzle");
const journal = JSON.parse(readFileSync(path.join(folder, "meta/_journal.json"), "utf8")) as {
entries: Array<{ tag: string }>;
};
for (const { tag: name } of journal.entries) {
const sql = readFileSync(path.join(folder, `${name}.sql`), "utf8");
for (const statement of sql.split("--> statement-breakpoint")) {
const trimmed = statement.trim();
if (trimmed.length > 0) await prisma.$executeRawUnsafe(trimmed);
}
}
}

Comment on lines +195 to +202
/**
* The persisted spec adds a server-set `since` to the caller's spec. It's the
* watch's creation time (ISO), used by `error_recurrence` so a recurrence check
* can't match errors that predate the watch. Stored inside the JSONB rather than
* as a column because it's part of the check's input, not watch lifecycle state.
*/
export type PersistedWatchSpec = WatchSpec & { since?: string };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd -t f 'schema.ts' internal-packages/dashboard-agent-db --exec rg -n 'PersistedWatchSpec' {}

Repository: triggerdotdev/trigger.dev

Length of output: 2073


🏁 Script executed:

#!/bin/bash
set -u

echo "PWD: $(pwd)"
echo "Top-level git availability:"
git rev-parse --show-toplevel 2>/dev/null || echo "git unavailable/not repo"

echo
echo "Find schema.ts candidates:"
fd -t f 'schema\.ts$' . 2>/dev/null | sed -n '1,50p' | grep -E 'internal-packages/dashboard-agent-db/src/schema\.ts|schema\.ts$' || true

echo
echo "Search PersistedWatchSpec in available files:"
if [ -d internal-packages/dashboard-agent-db/src ]; then
  rg -n 'PersistedWatchSpec' internal-packages/dashboard-agent-db/src 2>/dev/null || true
else
  echo "internal-packages/dashboard-agent-db/src not present"
fi

echo
echo "Context around internal-packages/dashboard-agent-db/src/schema.ts if present:"
if [ -f internal-packages/dashboard-agent-db/src/schema.ts ]; then
  sed -n '180,210p' internal-packages/dashboard-agent-db/src/schema.ts | cat -n
fi

Repository: triggerdotdev/trigger.dev

Length of output: 2044


🏁 Script executed:

#!/bin/bash
set -u
if [ ! -f internal-packages/dashboard-agent-db/src/schema.ts ]; then
  echo "target file missing from sandbox"
  exit 0
fi

python3 - <<'PY'
from pathlib import Path
line = 199  # likely line number for duplicate duplicate based on 201-202 snippet duplicate
path = Path("internal-packages/dashboard-agent-db/src/schema.ts")
text = path.read_text()
needle = "export type PersistedWatchSpec = WatchSpec & { since?: string };"
parts = text.splitlines()
for n, s in enumerate(parts, 1):
    if "PersistedWatchSpec" in s:
        print(f"{n}: {s}")
print("\n occurrences:", len([s for s in parts if needle in s]))
print("around 190-205:")
for n, s in enumerate(parts[189:204], 190):
    print(f"{n}: {s}")
PY

Repository: triggerdotdev/trigger.dev

Length of output: 2044


Duplicate PersistedWatchSpec declaration.

internal-packages/dashboard-agent-db/src/schema.ts declares export type PersistedWatchSpec = WatchSpec & { since?: string }; twice in the same module, which causes a duplicate identifier compile error. Remove the duplicate declaration.

The M5 entry-point list promised it; only the error-group page had it.
… buttons

A superlative question is answered in words with the top item's name and
number; the chart illustrates. The chart block gains up to three actions
(ask — the user's own follow-up, or navigate with a canonical trigger://
target), rendered as buttons under the chart and wired through the
panel's existing intent handling. A navigate target is a plain string at
the input boundary and a non-parsing one costs the button, never the
tool call.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/webapp/app/presenters/v3/ApiAlertChannelPresenter.server.ts (1)

15-22: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Gate dashboard_agent_watch from API alert-channel creation.

api.v1.projects.<projectRef>.alertChannels parses dashboard_agent_watch via ApiCreateAlertChannel, maps it to DASHBOARD_AGENT_WATCH, and persists it in the enabled alert channel. Add the same canAccessDashboardAgent check used by the web app/agent alert path before saving that type, since PAT/API users can otherwise subscribe an enabled channel to watch alerts without dashboard-agent access.

🟡 Minor comments (14)
apps/webapp/app/services/uatRoutePreamble.server.ts-31-34 (1)

31-34: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Accept case-insensitive Bearer schemes.

/^Bearer / rejects valid lowercase bearer authorization schemes, causing UAT requests to fall through and be rejected. Match the scheme case-insensitively.

Proposed fix
-    ?.replace(/^Bearer /, "")
+    ?.replace(/^Bearer\s+/i, "")
internal-packages/dashboard-agent-contracts/src/blocks.ts-470-525 (1)

470-525: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Two prose invariants aren't enforced alongside the two that are.

The superRefine enforces "remediation ⇒ concluded" and "checkNext ⇒ inconclusive", but:

  • checkNext is guarded by length > 0 while remediation is guarded only by !== undefined, so checkNext: [] passes on a concluded investigation whereas remediation: "" is rejected on an inconclusive one. The asymmetry lets a model send an empty checkNext on any outcome.
  • progress's description says "Only while in_progress" (Line 486) but nothing rejects it on a terminal outcome, so a concluded card can still carry a live-progress string that the renderer may show.

Both are model-supplied fields, so the schema is the only gate.

🛠️ Proposed tightening
-      if (investigation.remediation !== undefined && investigation.outcome !== "concluded") {
+      if (investigation.remediation?.trim() && investigation.outcome !== "concluded") {
         ctx.addIssue({
           code: z.ZodIssueCode.custom,
           path: ["remediation"],
           message: "Only a concluded investigation can offer a fix.",
         });
       }
-      if (
-        investigation.checkNext !== undefined &&
-        investigation.checkNext.length > 0 &&
-        investigation.outcome !== "inconclusive"
-      ) {
+      if (investigation.checkNext?.length && investigation.outcome !== "inconclusive") {
         ctx.addIssue({
           code: z.ZodIssueCode.custom,
           path: ["checkNext"],
           message: "`checkNext` belongs to an inconclusive investigation.",
         });
       }
+      if (investigation.progress?.trim() && investigation.outcome !== "in_progress") {
+        ctx.addIssue({
+          code: z.ZodIssueCode.custom,
+          path: ["progress"],
+          message: "`progress` only belongs to an in_progress investigation.",
+        });
+      }
internal-packages/dashboard-agent-contracts/src/watch.ts-29-34 (1)

29-34: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

maxHours accepts fractional values below one cadence interval.

z.number().positive().max(24) admits e.g. 0.01, which yields an expiresAt earlier than the minimum 1-minute cadence — the first tick is then already final and the watch immediately expires as "not met by expiry". Since this value comes from the model, an integer floor of 1 keeps the lifecycle sane.

🛡️ Proposed fix
-  maxHours: z.number().positive().max(WATCH_MAX_HOURS),
+  maxHours: z.number().int().min(1).max(WATCH_MAX_HOURS),
apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts.new/route.tsx-460-471 (1)

460-471: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

The "Dashboard agent watches" checkbox isn't feature-gated. Every project sees this option, including orgs without dashboard-agent access, where the alert type can never fire. Consider gating it on the same access check the rest of the feature uses (surface a flag from the loader).

apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts-396-404 (1)

396-404: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Scalar fact values are never length-capped.

The doc comment promises "a cap so a big bag can't blow up an email or a Slack block", but only object values are truncated — String(value) for a long string passes through unbounded. An oversized fact produces an invalid Slack block, which #postSlackMessage maps to invalid_blocksSkipRetryError, silently dropping the notification.

🐛 Proposed fix
     .map(([key, value]) => ({
       label: humanizeFactKey(key),
-      value: typeof value === "object" ? JSON.stringify(value).slice(0, 200) : String(value),
+      value: (typeof value === "object" ? JSON.stringify(value) : String(value)).slice(0, 200),
     }));
apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts-527-573 (1)

527-573: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

watchCreatedAndWake mixes two unrelated watch scenarios.

The title ("Tell me when the backlog drains"), the intent object (demoIntents.watch, which wraps demoBacklogDrainWatch.spec — 5 min checks for up to 6h, queue demo-backlog-drain), and the headerWatches/{kind:"watches"} items (demoWatches.activeRow, which includes demoBacklogDrainWatch) all describe the backlog-drain watch. But the actual user message ("Tell me when the retry finishes"), assistant confirmation ("I'll check every minute for up to 2 hours"), and wake narration are all about demoRunFinishedWatch (the run-retry watch) instead. The cadence numbers in the intent's outcome text (5 min/6h) directly contradict the assistant's own text (1 min/2h) a few lines later.

This reads as if the chat was repurposed from a backlog-drain story to a run-retry story without updating the title/intent/watches references.

apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts-726-762 (1)

726-762: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

docsAnswer title doesn't match its content.

Title is "How do I use batchTrigger?" but the user question, the search_docs tool call, and the entire answer are about retry/exponential-backoff behavior — batchTrigger is never mentioned.

🐛 Suggested fix
-  title: "How do I use batchTrigger?",
+  title: "How do retries actually work?",
apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts-478-500 (1)

478-500: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

navigateRejectedIntent title doesn't match its content.

Title is "Take me to my deployments" (a navigation request), but the actual turn is "Just fix it for me" being rejected via demoIntents.proposeFix — unrelated to deployments or navigation. This is the history-list title, so it will mislead anyone browsing the demo chat registry in Storybook.

🐛 Suggested fix
-  title: "Take me to my deployments",
+  title: "Just fix it for me",
apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts-180-230 (1)

180-230: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

investigateConcluded narration undercounts the hypotheses it actually tested.

The summary ("four tested hypotheses," line 185), the reasoning part ("Four candidates... run all four," lines 197-199), and the closing text ("Two of the four hold up," line 224) all describe a 4-hypothesis investigation. But demoInvestigationConcluded in fixtures/investigation.ts (lines 245-286) actually has 5 hypotheses — it also includes hyp-queue-burst (validated), so 3 of 5 hold up, not 2 of 4. The remediation text (line 244, "cap the queue's concurrency...") relies on that 5th hypothesis, so the data looks like the intended/complete version and the narration is stale.

For contrast, the sibling investigateInconclusive chat correctly matches its narration to its 3-hypothesis fixture, so this looks like an oversight specific to this chat rather than an intentional simplification.

🐛 Suggested fix
-          reasoningPart(
-            "Four candidates: the provider's rate limit, a bad payload, the retry schedule, and yesterday's deploy. Each one has a check that can rule it out, so run all four before writing a conclusion."
-          ),
+          reasoningPart(
+            "Five candidates: the provider's rate limit, a bad payload, the retry schedule, yesterday's deploy, and the queue bursting into the provider. Each one has a check that can rule it out, so run all five before writing a conclusion."
+          ),

and update the closing text/summary counts ("three of the five hold up") to match.

apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts-575-617 (1)

575-617: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

watchExpiryAndCancel narration miscounts the watches shown.

The opening narration says: "Four watches from this conversation... One is still live... the rest have finished." But demoWatches.row (used for both headerWatches and the {kind:"watches"} item) has 5 entries, and 2 of them (demoRunFinishedWatch and demoBacklogDrainWatch) are active, not 1. So the actual chip row a reviewer sees will show 5 chips with 2 active ones, contradicting the "four... one still live" framing.

🐛 Suggested fix Either narrate 5 watches with 2 still live, or scope the displayed row to the 4 the story actually describes (excluding `demoBacklogDrainWatch`, which belongs to a different scenario):
-{ kind: "watches", watches: demoWatches.row },
+{ kind: "watches", watches: [demoRunFinishedWatch, demoErrorRecurrenceWatch, demoHealthRecoveryWatch, demoCancelledWatch] },
internal-packages/dashboard-agent/src/tools.ts-429-448 (1)

429-448: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

await res.text() can throw past the { error } contract.

The fetch is guarded, but body reading isn't. On an abort (the 30s timeout at Line 1177) or a mid-stream socket reset, res.text() rejects and the exception escapes searchTriggerDocs, so search_docs throws instead of returning { error } — the convention this file states explicitly elsewhere ("Tools return {error}, never throw").

🛡️ Proposed fix
   if (!res.ok) return { error: `The docs search failed (status ${res.status}).` };
 
-  const body = await res.text();
+  let body: string;
+  try {
+    body = await res.text();
+  } catch (error) {
+    return { error: `Couldn't read the docs response: ${(error as Error).message}` };
+  }
   let payload: any;
apps/webapp/app/components/dashboard-agent/agent-badges.tsx-46-46 (1)

46-46: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use React’s component prop typing for the badge icon map.

@heroicons/react exports ForwardRefExoticComponent, not a function returning JSX.Element, so the direct assignments at lines 99, 127, and 155 may fail typecheck. Type this as React.ComponentType<{ className?: string }> instead.

apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx-163-180 (1)

163-180: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Render citation same-origin paths in a client-only SSR-safe way.

sameOriginPath(...) cannot work during SSR because location is browser-only, while window is falsy in the server pass. For same-origin citations, wrap this in ClientOnly/SSR-safe rendering so SSR passes the browser-ready Button branch and avoids a new-tab LinkButton vs client Button mismatch.

apps/webapp/app/components/dashboard-agent/suggested-prompts/promotedPrompt.server.ts-26-36 (1)

26-36: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Isolate the decorated flag read so the promoted chip can’t fail the environment layout.

makeFlag() reads prisma.featureFlag.findFirst() without catching Prisma failures, and this helper is awaited directly from the environment page loader. A flag-store hiccup on this optional, unsupported chip can turn the whole page into a 500, so catch and return undefined instead.

🛡️ Proposed fix
-  const flag = makeFlag();
-  const value = await flag({
-    key: FEATURE_FLAG.promotedDashboardAgentPrompt,
-    overrides: options?.orgFeatureFlags ?? {},
-  });
-
-  return parsePromotedPrompt(value);
+  try {
+    const flag = makeFlag();
+    const value = await flag({
+      key: FEATURE_FLAG.promotedDashboardAgentPrompt,
+      overrides: options?.orgFeatureFlags ?? {},
+    });
+
+    return parsePromotedPrompt(value);
+  } catch {
+    // A missing promoted chip is a supported state; a flag-store hiccup must not
+    // fail the layout loader.
+    return undefined;
+  }
🧹 Nitpick comments (26)
apps/webapp/seed-agent-examples.mts (1)

2267-2296: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Wrap the tick in a try/catch so one transient failure doesn't end the heartbeat.

The loop awaits heartbeatTick with no error handling, and heartbeatTick itself has failure modes that are likely over a multi-hour run: prisma.taskRun.update on executingRunId (Lines 2145-2150) throws P2025 once that row is gone (e.g. a re-seed or manual delete), and the ClickHouse insert helpers call process.exit(1). Net effect: the stand silently stops being refreshed and the report ages into "stale telemetry" — exactly what heartbeat mode exists to prevent.

♻️ Suggested resilience for the tick loop
     const counts: string[] = [];
     for (const env of envs) {
-      const result = await heartbeatTick(ch, env, started, rng, nonce, tick, mode);
-      counts.push(
-        `${env.environment.slug} +${result.runs} runs +${result.metricRows} metric rows` +
-          (result.pruned > 0 ? ` -${result.pruned} pruned` : "")
-      );
+      try {
+        const result = await heartbeatTick(ch, env, started, rng, nonce, tick, mode);
+        counts.push(
+          `${env.environment.slug} +${result.runs} runs +${result.metricRows} metric rows` +
+            (result.pruned > 0 ? ` -${result.pruned} pruned` : "")
+        );
+      } catch (error) {
+        counts.push(
+          `${env.environment.slug} tick failed: ${error instanceof Error ? error.message : error}`
+        );
+      }
     }

And make the executing-run touch tolerant of a missing row:

   if (env.executingRunId) {
-    await prisma.taskRun.update({
-      where: { id: env.executingRunId },
-      data: { updatedAt: new Date(now) },
-    });
+    const { count } = await prisma.taskRun.updateMany({
+      where: { id: env.executingRunId },
+      data: { updatedAt: new Date(now) },
+    });
+    if (count === 0) env.executingRunId = null;
   }
internal-packages/dashboard-agent/src/watch-tick.ts (1)

139-155: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Validate body.result against watchCheckResultSchema instead of casting.

body.result is cast to WatchCheckResult with no runtime check, and only three of the four values are matched explicitly in runWatchTick. Any unexpected string falls into the pending branch and the watch keeps ticking until expiry. The contracts package already exports the enum schema.

♻️ Proposed change
-import type { WatchCheckResult } from "`@internal/dashboard-agent-contracts`";
+import { watchCheckResultSchema } from "`@internal/dashboard-agent-contracts`";
+import type { WatchCheckResult } from "`@internal/dashboard-agent-contracts`";
-  if (!body?.result) return { kind: "unavailable", detail: "the check returned no result" };
-  if (body.result === "unavailable") return { kind: "unavailable", detail: body.error };
-  return { kind: "result", result: body.result, facts: body.facts };
+  const result = watchCheckResultSchema.safeParse(body?.result);
+  if (!result.success) {
+    return { kind: "unavailable", detail: "the check returned no usable result" };
+  }
+  if (result.data === "unavailable") return { kind: "unavailable", detail: body?.error };
+  return { kind: "result", result: result.data, facts: body?.facts };
internal-packages/dashboard-agent-contracts/src/watch.ts (1)

38-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use z.discriminatedUnion("kind", …) for watchSpecSchema.

Each variant already has a kind discriminator, and this is the validated model input, so the targeted faster parsing and branch-specific validation error are worthwhile.

♻️ Proposed change
-export const watchSpecSchema = z.union([
+export const watchSpecSchema = z.discriminatedUnion("kind", [
internal-packages/dashboard-agent-db/src/queries.ts (1)

600-609: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use type aliases for these data shapes.

ActiveWatchSummary, UnreadWatchWake, and ChatWatchContext are plain data shapes, not behavioral contracts.

As per coding guidelines: "Use types over interfaces for TypeScript".

♻️ Proposed change
-export interface ActiveWatchSummary {
+export type ActiveWatchSummary = {

(and likewise for UnreadWatchWake / ChatWatchContext)

Also applies to: 701-709, 790-794

Source: Coding guidelines

internal-packages/dashboard-agent/VERDICTS.md (1)

70-71: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Point the {env} citation at trigger-uri.ts.

trigger-uri.ts is where the trigger:// URI grammar is defined and documents {env} as the RuntimeEnvironment id; page-context.ts only defines the page-context schema.

internal-packages/dashboard-agent/src/dashboard-agent.test.ts (1)

414-433: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Fixed 30 ms sleep can flake on loaded CI. onTurnComplete enqueues asynchronously; a hard-coded delay is the only thing keeping these three assertions honest. Consider polling with a short deadline instead.

♻️ Poll instead of sleeping
-    await harness.sendMessage(userMessage("hi"));
-    // onTurnComplete enqueues after the turn-complete chunk; give it a tick.
-    await new Promise((r) => setTimeout(r, 30));
-    return calls;
+    await harness.sendMessage(userMessage("hi"));
+    // onTurnComplete enqueues after the turn-complete chunk; wait for it (or
+    // settle) rather than betting on a fixed delay.
+    const deadline = Date.now() + 2000;
+    while (calls.length === 0 && Date.now() < deadline) {
+      await new Promise((r) => setTimeout(r, 10));
+    }
+    return calls;

Note the rate-0 case still needs a short settle window, so keep a small final tick for it.

apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.ts (1)

66-73: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Second deployment lookup is redundant and replica-lag prone.

resolveRunCommit already reads the deployment row with git selected on the primary (apps/webapp/app/services/dashboardAgent.server.ts Lines 224–229), then this route re-reads the same row from $replica keyed by version. Besides the extra query, a freshly created deployment that resolved on the primary may not be visible on the replica yet, silently dropping shortCode/deployedAt/git from the response. Consider having resolveRunCommit return the git metadata (and shortCode/deployedAt) it already has.

apps/webapp/test/dashboardAgentRoutes.test.ts (1)

26-29: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

This env.server mock is a no-op that still loads the real module.

importOriginal() evaluates ~/env.server, so its env-var validation runs and the suite depends on the ambient environment — while the mock itself changes nothing. Either drop the vi.mock entirely or return explicit stub values for the keys the routes read.

As per path instructions: "Do not import env.server.ts directly or indirectly into test files; instead pass environment-dependent values through options/parameters to make code testable".

Source: Path instructions

apps/webapp/test/dashboardAgentWatches.test.ts (2)

83-83: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Don't import env.server in the test; pass the signing secret in.

env is only used at Line 676 to read SESSION_SECRET for signDashboardAgentWatchToken. Use a literal test secret so the suite doesn't depend on the real env module loading and validating.

As per coding guidelines: "Test files must not import app/env.server.ts; pass configuration as options instead."

♻️ Proposed change
-const { env } = await import("~/env.server");
+const TEST_SESSION_SECRET = "test-session-secret";
   function tokenFor(watchId: string, expiresAt: Date) {
-    return signDashboardAgentWatchToken(env.SESSION_SECRET, { watchId, expiresAt });
+    return signDashboardAgentWatchToken(TEST_SESSION_SECRET, { watchId, expiresAt });
   }

Note: the route verifies with the real env.SESSION_SECRET, so this only works if the route's secret is also injected or the test sets process.env.SESSION_SECRET before import — worth confirming which seam you prefer.

Source: Coding guidelines


92-104: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Lexicographic migration ordering is fragile.

readdirSync().sort() matches the journal order only while every filename keeps a zero-padded numeric prefix. drizzle/meta/_journal.json is the authoritative order — reading idx/tag from it would make this replay correct by construction rather than by convention.

apps/webapp/app/services/dashboardAgentWatchChecks.ts (1)

102-122: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the shared FINAL_RUN_STATUSES set for run terminality.

FINAL_STATUSES duplicates apps/webapp/app/v3/taskStatus.FINAL_RUN_STATUSES and can silently drift if a terminal status changes. Since this file only imports isomorphic utilities for ErrorId and durations, avoid importing the mostly server-side ~/v3/taskStatus module here; instead split the shared status constants/constants into an isomorphic helper and import it from this module.

apps/webapp/app/routes/api.v1.queues.$queueParam.metrics.ts (1)

23-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Narrow UNIT_MS so period multiplications stay type-exact.

UNIT_MS is annotated as Record<string, number>, and these app configs enable strict mode but not noUncheckedIndexedAccess, so the * in UNIT_MS[p.slice(-1)] and UNIT_MS.d is typed as number regardless of the actual key set. Use a keyed PeriodUnit value and narrow the index so the compiler rejects invalid suffixes before they can affect the refiner or periodMs().

Also applies to: 42-44

apps/webapp/app/routes/storybook.agent-ui/route.tsx (1)

437-459: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Orphaned doc comment: the URI-resolver doc is attached to investigationBlock.

The block at Lines 437-441 documents fixtureResolveUri, but that function is defined at Line 518; here it sits immediately above a second JSDoc for investigationBlock, leaving two stacked comments and the resolver undocumented at its definition.

♻️ Move the resolver doc to its definition
-/**
- * The gallery's stand-in for the panel's URI resolver. In the app the host
- * resolves against the real environment (`resolveTriggerUri.server.ts`); here a
- * fixture resolver proves the seam exists without a project route.
- */
 /**
  * The demo investigation fixtures, as the real `investigation` block: the demo

And at Line 518:

+/**
+ * The gallery's stand-in for the panel's URI resolver. In the app the host
+ * resolves against the real environment (`resolveTriggerUri.server.ts`); here a
+ * fixture resolver proves the seam exists without a project route.
+ */
 function fixtureResolveUri(uri: string): { label: string; url: string } | null {
apps/webapp/scripts/agent-ui-screenshots.ts (1)

220-243: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Panel presence check may short-circuit when the panel is in the DOM but hidden.

openPanel returns early on count() > 0, so if the panel element persists while closed (e.g. mounted but translated/hidden), the launcher is never clicked and the subsequent capture(panel) screenshots a collapsed element. Gating on visibility instead is more robust for the chat walk.

🛠️ Gate on visibility
-  const panel = page.locator(PANEL_SELECTOR);
-  if (!(await panel.count())) {
+  const panel = page.locator(PANEL_SELECTOR);
+  if (!(await panel.isVisible().catch(() => false))) {
apps/webapp/app/components/dashboard-agent/demo/fixtures/intents.ts (1)

71-74: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Avoid duplicating the investigation id as a string literal.

investigationId: "demo:investigation-order-receipt" duplicates what fixtures/investigation.ts already computes as demoId("investigation-order-receipt") for demoInvestigationConcluded. Importing that value avoids silent drift if the investigation fixture's id is ever renamed.

♻️ Suggested fix
-import { isExecutableIntent, type AgentIntent } from "`@internal/dashboard-agent-contracts`";
+import { isExecutableIntent, type AgentIntent } from "`@internal/dashboard-agent-contracts`";
+import { demoInvestigationConcluded } from "./investigation";
 import { DEMO_WORLD, demoRunUri } from "../ids";
 ...
 export const demoProposeFixIntent = demoIntent(
-  { kind: "propose_fix", investigationId: "demo:investigation-order-receipt" },
+  { kind: "propose_fix", investigationId: demoInvestigationConcluded.investigationId },
   "Rejected: proposing a fix isn't available yet"
 );
apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx (1)

79-81: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Raw indigo palette classes bypass the theme-remapping layer. Both new styles hardcode Tailwind palette classes, while agent-badges.tsx (lines 30-31) and report-sparkline.tsx (lines 39-40) added in this same PR explicitly state that palette classes are tuned for the dark theme only and that semantic tokens are what the theme layer remaps.

  • apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx#L79-L81: replace LINK_STYLE's text-indigo-500 hover:text-indigo-400 with the text-text-link token already used by InvestigationCard.tsx (line 89) and ReportFooterLink.
  • apps/webapp/app/components/primitives/Callout.tsx#L63-L70: give the agent variant a semantic token (e.g. a callout-agent token alongside the existing callout-docs/callout-pricing tokens) instead of border-indigo-500/20, bg-indigo-500/10 and text-indigo-500.
apps/webapp/app/components/primitives/Callout.tsx (1)

63-70: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Raw indigo palette classes won't be remapped by the theme layer.

Every other variant in this map uses semantic tokens (callout-docs, success, warning, error); the agent frame and icon hardcode indigo-500. See the consolidated note with RunDiagnosisCard.tsx for the shared fix.

apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx (1)

117-140: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Raw "output-error" string literal comparison.

p.state === "output-error" is compared as a raw literal here; the same literal is duplicated in report-block-adapter.ts and AgentMessageView.tsx. See consolidated comment for a shared-constant suggestion.

Source: Coding guidelines

apps/webapp/app/components/dashboard-agent/chat-layout.tsx (1)

236-284: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

ChatToolRow/ChatStatusLine don't self-apply the transcript inset when mounted loose.

Per rule 2 in this file's own docstring, a micro-layout mounted outside a ChatTurn must apply the inset itself (ChatProgress, ChatPendingTool, ChatNote all do this via useInsetClass()). ChatToolRow and ChatStatusLine don't call useInsetClass(), so if either is ever mounted loose (e.g. a tool row under a card), it will render without the horizontal inset, breaking alignment with the rest of the transcript. Neither is exercised in this diff yet, so confirm whether they're intentionally turn-only.

apps/webapp/app/components/dashboard-agent/report-block-adapter.ts (1)

50-56: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Raw "output-available" string literal comparison.

Same sentinel-value pattern as in DashboardAgentMessages.tsx and AgentMessageView.tsx — see consolidated comment.

Source: Coding guidelines

apps/webapp/app/components/runs/v3/agent/AgentMessageView.tsx (2)

164-188: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Raw tool-part state string literals.

This function is the biggest concentration of raw AI-SDK tool-part state comparisons ("output-error", "input-streaming", "input-available", "approval-requested", "approval-responded", "output-denied") in the reviewed diff. See consolidated comment for a shared-constant suggestion.

Source: Coding guidelines


1-1: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Extract shared named constants for AI-SDK tool-part state strings.

AgentMessageView.tsx, DashboardAgentMessages.tsx, and report-block-adapter.ts each independently compare p.state against raw literals ("output-error", "output-available", "input-streaming", "input-available", "approval-requested", "approval-responded", "output-denied"). progress-line.ts's IN_FLIGHT_TOOL_STATES already shows the right pattern for two of these; extending it (or a sibling constants module) to cover the rest would remove the duplication and the risk of a typo silently breaking one of these comparisons in a state machine that several files rely on independently.

  • apps/webapp/app/components/runs/v3/agent/AgentMessageView.tsx#L164-188: replace the raw "output-error", "input-streaming", "input-available", "approval-requested", "approval-responded", "output-denied" literals with shared named constants.
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx#L117-140: replace the raw "output-error" literal in renderDashboardPart with the same shared constant.
  • apps/webapp/app/components/dashboard-agent/report-block-adapter.ts#L50-56: replace the raw "output-available" literal with the same shared constant.

Source: Coding guidelines

apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.server.ts (1)

153-161: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Carry-forward seed of 0 can understate early buckets.

Buckets before the first emission are filled with 0 rather than left unknown, so a queue whose first metric row lands mid-window renders a fake "empty then spike" shape in the sparkline. sampleBuckets protects the ETA, but the series itself is user-visible. Consider starting from the first observed bucket (e.g. skip leading positions until byIndex has a value, or backfill with the first known depth).

apps/webapp/app/components/dashboard-agent/suggested-prompts/registry.ts (1)

217-222: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

SIGNAL_PRIORITY is not exhaustiveness-checked, unlike SIGNAL_SLOT.

Both contextualPrompts and contextualPromptsBySlot iterate SIGNAL_PRIORITY, so a signal kind added to the contract but omitted here produces no chip at all — silently, since AgentPageSignalKind[] accepts a partial list. SIGNAL_SLOT (a Record) would fail to compile in the same situation; make the priority list fail the same way.

♻️ Force a compile error on a missing kind
-export const SIGNAL_PRIORITY: AgentPageSignalKind[] = [
+export const SIGNAL_PRIORITY = [
   "fresh_failure",
   "waiting_run",
   "slow_run",
   "concurrency_saturation",
-];
+] as const satisfies readonly AgentPageSignalKind[] &
+  Record<0 | 1 | 2 | 3, AgentPageSignalKind>;

Simpler alternative: derive it from the SIGNAL_SLOT keys and sort, or add a type-level assertion that the union of SIGNAL_PRIORITY[number] equals AgentPageSignalKind.

apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.ts (1)

164-172: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

This assertion becomes a tautology if the fixture's page kind changes.

toContain("") always passes, so the branch is silently self-disabling — exactly the case the throw new Error("fixture changed") guards elsewhere in this file (lines 223, 228) exist to prevent. Narrow first instead.

💚 Proposed fix
-    const [failure] = resolveSuggestedPrompts(demoPageContexts.failedRun, { now: NOW });
-
-    expect(failure?.label).toBe("Why did this run fail?");
-    expect(failure?.prompt).toContain(
-      demoPageContexts.failedRun.page.kind === "run" ? demoPageContexts.failedRun.page.runId : ""
-    );
-    expect(failure?.prompt).toContain("12m ago");
+    const page = demoPageContexts.failedRun.page;
+    if (page.kind !== "run") throw new Error("fixture changed");
+    const [failure] = resolveSuggestedPrompts(demoPageContexts.failedRun, { now: NOW });
+
+    expect(failure?.label).toBe("Why did this run fail?");
+    expect(failure?.prompt).toContain(page.runId);
+    expect(failure?.prompt).toContain("12m ago");
apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.ts (1)

67-67: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Truncation drops the docs chip, contradicting the "always last, always present" invariant.

slice(0, CAP) cuts from the tail, and docs is the last slot. Today the cap presumably equals the slot count, so nothing is dropped — but if SUGGESTED_PROMPT_CAP is ever lowered, the documented guarantee (this file's header, and registry.ts line 14) silently breaks in favour of a lower-priority chip. Reserving the docs slot before the cap, or asserting CAP >= PROMPT_SLOTS.length + 1 at module load, keeps the invariant honest.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1060fc18-ba04-495e-8289-4498890ecfe7

📥 Commits

Reviewing files that changed from the base of the PR and between 6e5f0f0 and e7fafbf.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (209)
  • .server-changes/dashboard-agent-first-turn-error.md
  • .server-changes/dashboard-agent-investigate.md
  • .server-changes/dashboard-agent-watch-alerts.md
  • .server-changes/dashboard-agent-watches.md
  • .server-changes/queue-metrics-api.md
  • .server-changes/remove-header-docs-buttons.md
  • apps/webapp/.gitignore
  • apps/webapp/app/components/dashboard-agent/AgentChart.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgent.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentChat.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentComposer.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentContextBanner.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentDraft.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentHeader.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentHistory.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentSuggestedPrompts.tsx
  • apps/webapp/app/components/dashboard-agent/InvestigateButton.tsx
  • apps/webapp/app/components/dashboard-agent/InvestigationCard.test.ts
  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/ReportView.test.ts
  • apps/webapp/app/components/dashboard-agent/ReportView.tsx
  • apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx
  • apps/webapp/app/components/dashboard-agent/WakeBanner.tsx
  • apps/webapp/app/components/dashboard-agent/WatchChips.tsx
  • apps/webapp/app/components/dashboard-agent/WatchWakeToast.tsx
  • apps/webapp/app/components/dashboard-agent/agent-badges.tsx
  • apps/webapp/app/components/dashboard-agent/chat-layout.test.ts
  • apps/webapp/app/components/dashboard-agent/chat-layout.tsx
  • apps/webapp/app/components/dashboard-agent/dashboardAgentLauncher.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoIntentBubble.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoInvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoReportCard.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoSuggestedPromptsRow.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoWatchChips.tsx
  • apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts
  • apps/webapp/app/components/dashboard-agent/demo/demo.test.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/blocks.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/chart.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/index.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/intents.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/investigation.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/messages.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/page-context.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/reports.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/watches.ts
  • apps/webapp/app/components/dashboard-agent/demo/ids.ts
  • apps/webapp/app/components/dashboard-agent/demo/index.ts
  • apps/webapp/app/components/dashboard-agent/investigate-prompts.test.ts
  • apps/webapp/app/components/dashboard-agent/investigate-prompts.ts
  • apps/webapp/app/components/dashboard-agent/list-row.tsx
  • apps/webapp/app/components/dashboard-agent/message-order.test.ts
  • apps/webapp/app/components/dashboard-agent/message-order.ts
  • apps/webapp/app/components/dashboard-agent/navigate-target.test.ts
  • apps/webapp/app/components/dashboard-agent/navigate-target.ts
  • apps/webapp/app/components/dashboard-agent/page-context-types.ts
  • apps/webapp/app/components/dashboard-agent/page-label.test.ts
  • apps/webapp/app/components/dashboard-agent/page-label.ts
  • apps/webapp/app/components/dashboard-agent/progress-line.test.ts
  • apps/webapp/app/components/dashboard-agent/progress-line.ts
  • apps/webapp/app/components/dashboard-agent/report-block-adapter.test.ts
  • apps/webapp/app/components/dashboard-agent/report-block-adapter.ts
  • apps/webapp/app/components/dashboard-agent/report-sparkline.tsx
  • apps/webapp/app/components/dashboard-agent/run-id.test.ts
  • apps/webapp/app/components/dashboard-agent/run-id.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/index.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.test.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promotedPrompt.server.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/registry.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.ts
  • apps/webapp/app/components/dashboard-agent/tool-labels.test.ts
  • apps/webapp/app/components/dashboard-agent/tool-labels.ts
  • apps/webapp/app/components/dashboard-agent/useTranscriptAutoScroll.ts
  • apps/webapp/app/components/dashboard-agent/view-blocks.test.ts
  • apps/webapp/app/components/dashboard-agent/view-blocks.ts
  • apps/webapp/app/components/dashboard-agent/view-catalog.tsx
  • apps/webapp/app/components/dashboard-agent/watch-chips.test.ts
  • apps/webapp/app/components/dashboard-agent/watch-chips.ts
  • apps/webapp/app/components/metrics/MiniLineChart.tsx
  • apps/webapp/app/components/primitives/Callout.tsx
  • apps/webapp/app/components/runs/v3/agent/AgentMessageView.tsx
  • apps/webapp/app/hooks/useAgentPageContext.ts
  • apps/webapp/app/presenters/v3/ApiAlertChannelPresenter.server.ts
  • apps/webapp/app/presenters/v3/reports/health/health-messages.ts
  • apps/webapp/app/presenters/v3/reports/health/health.ts
  • apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.server.ts
  • apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.agents.$agentParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts.new/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.apikeys/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.batches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.deployments/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.errors.$fingerprint/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.limits/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.prompts._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions.$sessionParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.test/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.waitpoints.tokens/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections.new/route.tsx
  • apps/webapp/app/routes/account.tokens/route.tsx
  • apps/webapp/app/routes/api.v1.dashboard-agent.alerts.$channelId.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.fired.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.jwt.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.repo.snapshot.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.waiting.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.workers.$tagName.ts
  • apps/webapp/app/routes/api.v1.queues.$queueParam.metrics.ts
  • apps/webapp/app/routes/resources.dashboard-agent.alerts.$channelId.unsubscribe.tsx
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.in.$.ts
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.ts
  • apps/webapp/app/routes/storybook.agent-ui/manifest.ts
  • apps/webapp/app/routes/storybook.agent-ui/route.tsx
  • apps/webapp/app/routes/storybook.callout/route.tsx
  • apps/webapp/app/services/dashboardAgentAlertContext.server.ts
  • apps/webapp/app/services/dashboardAgentAlertUnsubscribeToken.server.ts
  • apps/webapp/app/services/dashboardAgentHeadStart.server.ts
  • apps/webapp/app/services/dashboardAgentWatchAlerts.server.ts
  • apps/webapp/app/services/dashboardAgentWatchChecks.server.ts
  • apps/webapp/app/services/dashboardAgentWatchChecks.ts
  • apps/webapp/app/services/dashboardAgentWatchToken.server.ts
  • apps/webapp/app/services/dashboardAgentWatches.server.ts
  • apps/webapp/app/services/resolveTriggerUri.server.ts
  • apps/webapp/app/services/uatRoutePreamble.server.ts
  • apps/webapp/app/utils/handle.ts
  • apps/webapp/app/v3/alertsWorker.server.ts
  • apps/webapp/app/v3/featureFlags.ts
  • apps/webapp/app/v3/services/alerts/deliverAlert.server.ts
  • apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts
  • apps/webapp/package.json
  • apps/webapp/scripts/agent-ui-screenshots.ts
  • apps/webapp/seed-agent-examples-chats.mts
  • apps/webapp/seed-agent-examples.mts
  • apps/webapp/seed-queue-metrics.mts
  • apps/webapp/test/dashboardAgentHeadStart.test.ts
  • apps/webapp/test/dashboardAgentRoutes.test.ts
  • apps/webapp/test/dashboardAgentWatchChecks.test.ts
  • apps/webapp/test/dashboardAgentWatchToken.test.ts
  • apps/webapp/test/dashboardAgentWatches.test.ts
  • apps/webapp/test/reportHealth.test.ts
  • apps/webapp/test/resolveTriggerUri.test.ts
  • apps/webapp/test/seedAgentExamplesChats.test.ts
  • apps/webapp/test/waitingRunDiagnosis.test.ts
  • apps/webapp/vitest.config.ts
  • internal-packages/dashboard-agent-contracts/package.json
  • internal-packages/dashboard-agent-contracts/src/blocks.test.ts
  • internal-packages/dashboard-agent-contracts/src/blocks.ts
  • internal-packages/dashboard-agent-contracts/src/contracts.test.ts
  • internal-packages/dashboard-agent-contracts/src/evidence.ts
  • internal-packages/dashboard-agent-contracts/src/index.ts
  • internal-packages/dashboard-agent-contracts/src/intent.ts
  • internal-packages/dashboard-agent-contracts/src/page-context.ts
  • internal-packages/dashboard-agent-contracts/src/run-filters.ts
  • internal-packages/dashboard-agent-contracts/src/suggested-prompts.ts
  • internal-packages/dashboard-agent-contracts/src/trigger-uri.test.ts
  • internal-packages/dashboard-agent-contracts/src/trigger-uri.ts
  • internal-packages/dashboard-agent-contracts/src/watch.test.ts
  • internal-packages/dashboard-agent-contracts/src/watch.ts
  • internal-packages/dashboard-agent-contracts/tsconfig.json
  • internal-packages/dashboard-agent-contracts/vitest.config.ts
  • internal-packages/dashboard-agent-db/README.md
  • internal-packages/dashboard-agent-db/drizzle/0002_luxuriant_king_cobra.sql
  • internal-packages/dashboard-agent-db/drizzle/0003_famous_champions.sql
  • internal-packages/dashboard-agent-db/drizzle/meta/0002_snapshot.json
  • internal-packages/dashboard-agent-db/drizzle/meta/0003_snapshot.json
  • internal-packages/dashboard-agent-db/drizzle/meta/_journal.json
  • internal-packages/dashboard-agent-db/package.json
  • internal-packages/dashboard-agent-db/src/ids.ts
  • internal-packages/dashboard-agent-db/src/index.ts
  • internal-packages/dashboard-agent-db/src/queries.ts
  • internal-packages/dashboard-agent-db/src/schema.ts
  • internal-packages/dashboard-agent/GUIDEBOOK.md
  • internal-packages/dashboard-agent/PLAYBOOK.md
  • internal-packages/dashboard-agent/VERDICTS.md
  • internal-packages/dashboard-agent/package.json
  • internal-packages/dashboard-agent/src/dashboard-agent.eval.ts
  • internal-packages/dashboard-agent/src/dashboard-agent.test.ts
  • internal-packages/dashboard-agent/src/dashboard-agent.ts
  • internal-packages/dashboard-agent/src/index.ts
  • internal-packages/dashboard-agent/src/tool-schemas.ts
  • internal-packages/dashboard-agent/src/tools.ts
  • internal-packages/dashboard-agent/src/watch-tick.test.ts
  • internal-packages/dashboard-agent/src/watch-tick.ts
  • internal-packages/dashboard-agent/vitest.eval.config.ts
  • internal-packages/database/prisma/migrations/20260729120000_add_dashboard_agent_watch_alert_type/migration.sql
  • internal-packages/database/prisma/schema.prisma
  • internal-packages/emails/emails/alert-dashboard-agent-watch.tsx
  • internal-packages/emails/src/index.tsx
💤 Files with no reviewable changes (1)
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx

Comment on lines +122 to +130
const gate = await canUseDashboardAgentEmailAlerts({
userId,
organizationId: environment.organizationId,
organizationSlug: environment.organization.slug,
projectId: environment.project.id,
});
if (!gate.allowed) {
return json({ error: "Alerts are not available here", code: gate.reason }, { status: 403 });
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd 'dashboardAgentWatchAlerts.server.ts' --exec cat -n {}
rg -nP --type=ts -C3 'canUseDashboardAgent(Email)?Alerts\s*\(' apps

Repository: triggerdotdev/trigger.dev

Length of output: 13203


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '--- locate canAccessDashboardAgent ---\n'
fd 'canAccessDashboardAgent.server.ts' --exec sh -c 'echo "### $1"; sed -n "1,220p" "$1" | cat -n' sh {}

printf '\n--- route slices ---\n'
for f in \
  apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts \
  apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts \
  apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts
do
  echo "### $f"
  lines="$(wc -l < "$f")"
  case "$f" in
    apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts) sed -n '80,140p' "$f" | cat -n ;;
    apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts) sed -n '145,205p' "$f" | cat -n ;;
    apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts) sed -n '60,120p' "$f" | cat -n ;;
  esac
done

Repository: triggerdotdev/trigger.dev

Length of output: 254


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- locate canAccessDashboardAgent ---'
fd 'canAccessDashboardAgent.server.ts' --exec sh -c 'echo "### $1"; sed -n "1,220p" "$1" | cat -n' sh {}

printf '%s\n' ''
printf '%s\n' '--- route slices ---'
for f in \
  apps/webapp/app/routes/api.v1.dashboard-agent	alerts.ts \
  apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts \
  apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts
do
  echo "### $f"
  case "$f" in
    'apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts') sed -n '80,140p' "$f" | cat -n ;;
    'apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts') sed -n '145,205p' "$f" | cat -n ;;
    'apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts') sed -n '60,120p' "$f" | cat -n ;;
  esac
done

Repository: triggerdotdev/trigger.dev

Length of output: 7125


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- all gate call sites with context ---'
rg -n -C 4 'canUseDashboardAgent(Email)?Alerts\s*\(' apps/webapp/app

printf '%s\n' ''
printf '%s\n' '--- imports and route context for alerts route ---'
f='apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts'
echo "### $f"
sed -n '1,150p' "$f" | cat -n

printf '%s\n' ''
echo "### apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts"
sed -n '1,130p' apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts | cat -n

printf '%s\n' ''
echo "### apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts"
sed -n '1,220p' apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts | cat -n

Repository: triggerdotdev/trigger.dev

Length of output: 26440


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- imports in alerts route'
sed -n '1,30p' apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts | cat -n

printf '%s\n' ''
printf '%s\n' '--- import path for authenticateAgentUatOrApiRequest if present'
rg -n 'authenticateAgentUatOrApiRequest|resolveAgentAlertContext|organization.*featureFlags|featureFlags.*organization|Authenticated' apps/webapp/app/services -g '*.server.ts' -g '*.ts' | head -n 200

Repository: triggerdotdev/trigger.dev

Length of output: 8407


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- dashboardAgentAlertContext.server.ts ---'
sed -n '1,220p' apps/webapp/app/services/dashboardAgentAlertContext.server.ts | cat -n

printf '%s\n' ''
printf '%s\n' '--- runtime environment auth slices mentioning organization select---'
rg -n -C 3 'authIncludeWithParent|toAuthenticated|organization.*featureFlags|featureFlags.*organization|authorizeWatchEnvironmentById|resolveAgentAlertContext' apps/webapp/app/services apps/webapp/app/models --glob '*.server.ts' --glob '*.ts' | head -n 300

Repository: triggerdotdev/trigger.dev

Length of output: 21181


Align dashboard-agent alert gating across subscribe and delivery. The email subscribe route resolves its context via authorizeWatchEnvironmentById, which surfaces the org featureFlags and would allow using that in the 403 gate; resolveEmailAlertsState already passes it, but the delivery job selects only organization: { slug, title } and calls the gate without orgFeatureFlags. Select loaded by-reference org flags at delivery and thread them to canUseDashboardAgentAlerts so an org feature-override can’t allow subscribing while denying delivery, or vice versa.

📍 Affects 3 files
  • apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts#L122-L130 (this comment)
  • apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts#L104-L108
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts#L180-L185

Source: Learnings

Comment thread apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts
Comment on lines +56 to +70
params: z.object({
queueParam: z.string().transform((val) => val.replace(/%2F/g, "/")),
}),
searchParams: SearchParamsSchema,
allowJWT: true,
corsStrategy: "none",
findResource: async () => 1, // dummy — the queue name isn't resolved against Postgres
authorization: {
action: "read",
resource: () => ({ type: "query", id: "queue_metrics" }),
},
},
async ({ params, searchParams, authentication }) => {
const name = decodeURIComponent(params.queueParam).replace(/%2F/g, "/");
const queue = searchParams.type === "task" && !name.startsWith("task/") ? `task/${name}` : name;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Queue name is decoded twice, and the second decode can throw a 500.

The params schema (Line 57) already unescapes %2F, and Remix has already URL-decoded the route param. Line 69 then runs decodeURIComponent on that value again plus a repeat %2F replace. Two consequences:

  • A queue name containing a literal % that isn't a valid escape (e.g. discount-100%) makes decodeURIComponent throw URIError. Line 69 sits outside the try that starts at Line 80, so it escapes the handler as an unhandled 500 rather than a 4xx.
  • Names with legitimately encoded characters get mangled by the extra decode pass.

Pick one place to normalize — the schema transform — and drop the second decode.

🐛 Proposed fix
     params: z.object({
-      queueParam: z.string().transform((val) => val.replace(/%2F/g, "/")),
+      // Remix has already URL-decoded the segment; only the `%2F` escape for the
+      // `task/` prefix survives and needs unescaping.
+      queueParam: z.string().transform((val) => val.replace(/%2F/gi, "/")),
     }),
-    const name = decodeURIComponent(params.queueParam).replace(/%2F/g, "/");
+    const name = params.queueParam;
     const queue = searchParams.type === "task" && !name.startsWith("task/") ? `task/${name}` : name;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
params: z.object({
queueParam: z.string().transform((val) => val.replace(/%2F/g, "/")),
}),
searchParams: SearchParamsSchema,
allowJWT: true,
corsStrategy: "none",
findResource: async () => 1, // dummy — the queue name isn't resolved against Postgres
authorization: {
action: "read",
resource: () => ({ type: "query", id: "queue_metrics" }),
},
},
async ({ params, searchParams, authentication }) => {
const name = decodeURIComponent(params.queueParam).replace(/%2F/g, "/");
const queue = searchParams.type === "task" && !name.startsWith("task/") ? `task/${name}` : name;
params: z.object({
// Remix has already URL-decoded the segment; only the `%2F` escape for the
// `task/` prefix survives and needs unescaping.
queueParam: z.string().transform((val) => val.replace(/%2F/gi, "/")),
}),
searchParams: SearchParamsSchema,
allowJWT: true,
corsStrategy: "none",
findResource: async () => 1, // dummy — the queue name isn't resolved against Postgres
authorization: {
action: "read",
resource: () => ({ type: "query", id: "queue_metrics" }),
},
},
async ({ params, searchParams, authentication }) => {
const name = params.queueParam;
const queue = searchParams.type === "task" && !name.startsWith("task/") ? `task/${name}` : name;

Comment on lines +179 to +193
const channel = await db.projectAlertChannel.findFirst({
where: { id: channelId, ...(options.projectId ? { projectId: options.projectId } : {}) },
select: { id: true, name: true, alertTypes: true },
});
if (!channel) return { ok: false, reason: "not_found" };

const remaining = channel.alertTypes.filter((type) => type !== DASHBOARD_AGENT_WATCH_ALERT_TYPE);

await db.projectAlertChannel.update({
where: { id: channel.id },
data: {
alertTypes: remaining,
...(remaining.length === 0 ? { enabled: false } : {}),
},
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Make the unsubscribe update atomic.

The read at Line 179 and overwrite at Lines 187-193 can race with alert-channel edits, dropping newly added alert types or disabling a channel that was concurrently updated. Use a conditional-update/retry strategy or a database-side atomic array removal; compute enabled in that same atomic operation. As per coding guidelines, use the $transaction helper from ~/db.server with Serializable for correctness-critical read-then-write invariants.

Source: Coding guidelines

Comment on lines +84 to +108
const environment = await $replica.runtimeEnvironment.findFirst({
where: {
id: params.environmentId,
// The watch's snapshot has to still describe this environment — a mismatch
// means the row is being used to reach somewhere it was never created for.
projectId: params.projectId,
organizationId: params.organizationId,
archivedAt: null,
project: { deletedAt: null },
organization: { deletedAt: null, members: { some: { userId: params.userId } } },
OR: [
{ type: { in: ["PREVIEW", "STAGING", "PRODUCTION"] } },
// Dev environments are per-member: only their owner may read them.
{ type: "DEVELOPMENT", orgMember: { userId: params.userId } },
],
},
include: authIncludeWithParent,
});

if (!environment) return { ok: false, reason: "access_revoked" };

const user = await $replica.user.findFirst({
where: { id: params.userId },
select: { admin: true },
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Re-authorization reads from $replica; use the primary client for the membership/tenant floor.

This query is the authorization boundary for every background tick (membership, live project, non-archived env, dev-owner), and replica lag makes it fail open: a membership that was just revoked, or an environment/project just archived/deleted, can still be visible on the replica, so the watch keeps firing with access the user no longer has. Same for the user.admin read feeding canAccessDashboardAgent. Read both from prisma and note why in a comment.

Based on learnings: whenever you resolve org/membership scope for RBAC/authorization, always read from the primary Prisma client (prisma), not $replica, because replica lag can cause the authorization check to run without the correct org scope.

🔒️ Proposed fix
-  const environment = await $replica.runtimeEnvironment.findFirst({
+  // Primary client on purpose: replica lag on a revoked membership or a freshly
+  // archived environment would let this re-authorization pass open.
+  const environment = await prisma.runtimeEnvironment.findFirst({
-  const user = await $replica.user.findFirst({
+  const user = await prisma.user.findFirst({

Update the import accordingly:

-import { $replica } from "~/db.server";
+import { $replica, prisma } from "~/db.server";
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const environment = await $replica.runtimeEnvironment.findFirst({
where: {
id: params.environmentId,
// The watch's snapshot has to still describe this environment — a mismatch
// means the row is being used to reach somewhere it was never created for.
projectId: params.projectId,
organizationId: params.organizationId,
archivedAt: null,
project: { deletedAt: null },
organization: { deletedAt: null, members: { some: { userId: params.userId } } },
OR: [
{ type: { in: ["PREVIEW", "STAGING", "PRODUCTION"] } },
// Dev environments are per-member: only their owner may read them.
{ type: "DEVELOPMENT", orgMember: { userId: params.userId } },
],
},
include: authIncludeWithParent,
});
if (!environment) return { ok: false, reason: "access_revoked" };
const user = await $replica.user.findFirst({
where: { id: params.userId },
select: { admin: true },
});
// Primary client on purpose: replica lag on a revoked membership or a freshly
// archived environment would let this re-authorization pass open.
const environment = await prisma.runtimeEnvironment.findFirst({
where: {
id: params.environmentId,
// The watch's snapshot has to still describe this environment — a mismatch
// means the row is being used to reach somewhere it was never created for.
projectId: params.projectId,
organizationId: params.organizationId,
archivedAt: null,
project: { deletedAt: null },
organization: { deletedAt: null, members: { some: { userId: params.userId } } },
OR: [
{ type: { in: ["PREVIEW", "STAGING", "PRODUCTION"] } },
// Dev environments are per-member: only their owner may read them.
{ type: "DEVELOPMENT", orgMember: { userId: params.userId } },
],
},
include: authIncludeWithParent,
});
if (!environment) return { ok: false, reason: "access_revoked" };
const user = await prisma.user.findFirst({
where: { id: params.userId },
select: { admin: true },
});

Source: Learnings

Comment on lines +1 to +6
import { prisma } from "./app/db.server";
import { createOrganization } from "./app/models/organization.server";
import { createProject } from "./app/models/project.server";
import { ClickHouse } from "@internal/clickhouse";
import type { QueueMetricsRawV1Input } from "@internal/clickhouse";
import { generateFriendlyId } from "./app/v3/friendlyIdentifiers";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Are these seeders declared as ESM entries, and how do the older ones import app modules?
fd -e mts . apps/webapp --max-depth 1
rg -n '"type"|db:seed' apps/webapp/package.json
rg -n '^import .* from "\./app/' apps/webapp/*.mts

Repository: triggerdotdev/trigger.dev

Length of output: 2326


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== apps/webapp/package.json scripts/types =="
python3 - <<'PY'
import json
from pathlib import Path
p=Path('apps/webapp/package.json')
data=json.loads(p.read_text())
for key in ['type','scripts']:
    print(f'{key}: {data.get(key)!r}')
PY

echo "== relevant seeder comments and import usage =="
for f in apps/webapp/seed-agent-examples.mts apps/webapp/seed-ai-spans.mts apps/webapp/seed-agent-examples-chats.mts apps/webapp/seed-queue-metrics.mts; do
  echo "--- $f (first 120 lines) ---"
  sed -n '1,120p' "$f" | cat -n
done

echo "== tsconfig/module hints for webapp if present =="
fd -e 'tsconfig.*' -e 'package.json' apps/webapp . | sed -n '1,80p'
rg -n '"esModuleInterop"|"allowSyntheticDefaultImports"|"module"|"moduleResolution"|tsx"|"database"' apps/webapp -g '!node_modules' -g '!dist' -g '!build' | sed -n '1,200p'

Repository: triggerdotdev/trigger.dev

Length of output: 25488


Use the default-binding import pattern for this .mts seeder.

apps/webapp has no "type": "module" and the seeder scripts compile app modules to CommonJS via tsx, so named imports from ./app/* can fail at startup. Align seed-queue-metrics.mts with seed-agent-examples.mts: import the compiled app modules as default bindings, then destructure the needed exports locally.

Comment on lines +6 to +12
import {
WATCH_TOKEN_GRACE_MS,
WATCH_TOKEN_PREFIX,
isDashboardAgentWatchToken,
signDashboardAgentWatchToken,
verifyDashboardAgentWatchToken,
} from "~/services/dashboardAgentWatchToken.server";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

This test pulls in env.server transitively.

~/services/dashboardAgentWatchToken.server.ts imports env from ~/env.server at module scope, so importing it here loads the env schema/validation even though every assertion passes an explicit SECRET. Split the pure crypto (WATCH_TOKEN_PREFIX, WATCH_TOKEN_GRACE_MS, signDashboardAgentWatchToken, verifyDashboardAgentWatchToken, isDashboardAgentWatchToken) into a non-.server module and keep only the env-bound mint…/verify…FromRequest wrappers in .server.ts — the same seam split this PR already uses for dashboardAgentWatchChecks.ts vs dashboardAgentWatchChecks.server.ts. The test then imports the pure module.

As per path instructions: test files under apps/webapp must not import app/env.server.ts directly or indirectly; pass environment-dependent values through options/parameters instead.

Source: Path instructions

Comment on lines +12 to +21
export const evidenceSchema = z.object({
/** What kind of resource this cites. Mirrors the URI's resource kinds. */
kind: triggerUriKindSchema,
/** The resource itself. */
uri: triggerUriSchema,
/** Short human label, e.g. "run_abc123 failed span" or "processOrder.ts:42". */
label: z.string(),
/** Optional verbatim snippet (error message, log line, source lines). */
excerpt: z.string().optional(),
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

kind isn't cross-checked against the URI's own kind.

{ kind: "queue", uri: "trigger://proj_a/env_a/run/run_1" } validates, so a citation can claim one resource type and point at another — the renderer picks its icon/label from kind but resolves the link from uri. The demo suite already asserts this invariant on fixtures (apps/webapp/app/components/dashboard-agent/demo/demo.test.ts Lines 141-148 compare safeParseTriggerUri(evidence.uri).data.kind to evidence.kind), but nothing enforces it at the parse boundary where model-derived evidence actually arrives.

🛡️ Proposed fix
 import { z } from "zod";
-import { triggerUriKindSchema, triggerUriSchema } from "./trigger-uri.js";
+import { safeParseTriggerUri, triggerUriKindSchema, triggerUriSchema } from "./trigger-uri.js";
 
-export const evidenceSchema = z.object({
+export const evidenceSchema = z
+  .object({
   /** What kind of resource this cites. Mirrors the URI's resource kinds. */
   kind: triggerUriKindSchema,
   /** The resource itself. */
   uri: triggerUriSchema,
   /** Short human label, e.g. "run_abc123 failed span" or "processOrder.ts:42". */
   label: z.string(),
   /** Optional verbatim snippet (error message, log line, source lines). */
   excerpt: z.string().optional(),
-});
+  })
+  .superRefine((evidence, ctx) => {
+    // A citation that claims one kind and points at another links the user
+    // somewhere other than what the card says it cites.
+    const parsed = safeParseTriggerUri(evidence.uri);
+    if (parsed.success && parsed.data.kind !== evidence.kind) {
+      ctx.addIssue({
+        code: z.ZodIssueCode.custom,
+        path: ["kind"],
+        message: `kind "${evidence.kind}" does not match the uri's kind "${parsed.data.kind}".`,
+      });
+    }
+  });

Note this makes evidenceSchema a ZodEffects, so any consumer relying on .extend()/.merge()/.shape on it would need adjusting — in the current code it's only used as an array element in blocks.ts, which is fine.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const evidenceSchema = z.object({
/** What kind of resource this cites. Mirrors the URI's resource kinds. */
kind: triggerUriKindSchema,
/** The resource itself. */
uri: triggerUriSchema,
/** Short human label, e.g. "run_abc123 failed span" or "processOrder.ts:42". */
label: z.string(),
/** Optional verbatim snippet (error message, log line, source lines). */
excerpt: z.string().optional(),
});
import { z } from "zod";
import { safeParseTriggerUri, triggerUriKindSchema, triggerUriSchema } from "./trigger-uri.js";
export const evidenceSchema = z
.object({
/** What kind of resource this cites. Mirrors the URI's resource kinds. */
kind: triggerUriKindSchema,
/** The resource itself. */
uri: triggerUriSchema,
/** Short human label, e.g. "run_abc123 failed span" or "processOrder.ts:42". */
label: z.string(),
/** Optional verbatim snippet (error message, log line, source lines). */
excerpt: z.string().optional(),
})
.superRefine((evidence, ctx) => {
// A citation that claims one kind and points at another links the user
// somewhere other than what the card says it cites.
const parsed = safeParseTriggerUri(evidence.uri);
if (parsed.success && parsed.data.kind !== evidence.kind) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["kind"],
message: `kind "${evidence.kind}" does not match the uri's kind "${parsed.data.kind}".`,
});
}
});

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1060fc18-ba04-495e-8289-4498890ecfe7

📥 Commits

Reviewing files that changed from the base of the PR and between 6e5f0f0 and fd5006e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (210)
  • .server-changes/dashboard-agent-first-turn-error.md
  • .server-changes/dashboard-agent-investigate.md
  • .server-changes/dashboard-agent-watch-alerts.md
  • .server-changes/dashboard-agent-watches.md
  • .server-changes/queue-metrics-api.md
  • .server-changes/remove-header-docs-buttons.md
  • apps/webapp/.gitignore
  • apps/webapp/app/components/dashboard-agent/AgentChart.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgent.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentChat.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentComposer.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentContextBanner.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentDraft.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentHeader.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentHistory.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentSuggestedPrompts.tsx
  • apps/webapp/app/components/dashboard-agent/InvestigateButton.tsx
  • apps/webapp/app/components/dashboard-agent/InvestigationCard.test.ts
  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/ReportView.test.ts
  • apps/webapp/app/components/dashboard-agent/ReportView.tsx
  • apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx
  • apps/webapp/app/components/dashboard-agent/WakeBanner.tsx
  • apps/webapp/app/components/dashboard-agent/WatchChips.tsx
  • apps/webapp/app/components/dashboard-agent/WatchWakeToast.tsx
  • apps/webapp/app/components/dashboard-agent/agent-badges.tsx
  • apps/webapp/app/components/dashboard-agent/chat-layout.test.ts
  • apps/webapp/app/components/dashboard-agent/chat-layout.tsx
  • apps/webapp/app/components/dashboard-agent/dashboardAgentLauncher.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoIntentBubble.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoInvestigationCard.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoReportCard.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoSuggestedPromptsRow.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoWatchChips.tsx
  • apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts
  • apps/webapp/app/components/dashboard-agent/demo/demo.test.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/blocks.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/chart.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/index.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/intents.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/investigation.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/messages.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/page-context.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/reports.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/watches.ts
  • apps/webapp/app/components/dashboard-agent/demo/ids.ts
  • apps/webapp/app/components/dashboard-agent/demo/index.ts
  • apps/webapp/app/components/dashboard-agent/investigate-prompts.test.ts
  • apps/webapp/app/components/dashboard-agent/investigate-prompts.ts
  • apps/webapp/app/components/dashboard-agent/list-row.tsx
  • apps/webapp/app/components/dashboard-agent/message-order.test.ts
  • apps/webapp/app/components/dashboard-agent/message-order.ts
  • apps/webapp/app/components/dashboard-agent/navigate-target.test.ts
  • apps/webapp/app/components/dashboard-agent/navigate-target.ts
  • apps/webapp/app/components/dashboard-agent/page-context-types.ts
  • apps/webapp/app/components/dashboard-agent/page-label.test.ts
  • apps/webapp/app/components/dashboard-agent/page-label.ts
  • apps/webapp/app/components/dashboard-agent/progress-line.test.ts
  • apps/webapp/app/components/dashboard-agent/progress-line.ts
  • apps/webapp/app/components/dashboard-agent/report-block-adapter.test.ts
  • apps/webapp/app/components/dashboard-agent/report-block-adapter.ts
  • apps/webapp/app/components/dashboard-agent/report-sparkline.tsx
  • apps/webapp/app/components/dashboard-agent/run-id.test.ts
  • apps/webapp/app/components/dashboard-agent/run-id.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/index.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.test.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promotedPrompt.server.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/registry.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.ts
  • apps/webapp/app/components/dashboard-agent/tool-labels.test.ts
  • apps/webapp/app/components/dashboard-agent/tool-labels.ts
  • apps/webapp/app/components/dashboard-agent/useTranscriptAutoScroll.ts
  • apps/webapp/app/components/dashboard-agent/view-blocks.test.ts
  • apps/webapp/app/components/dashboard-agent/view-blocks.ts
  • apps/webapp/app/components/dashboard-agent/view-catalog.tsx
  • apps/webapp/app/components/dashboard-agent/watch-chips.test.ts
  • apps/webapp/app/components/dashboard-agent/watch-chips.ts
  • apps/webapp/app/components/metrics/MiniLineChart.tsx
  • apps/webapp/app/components/primitives/Callout.tsx
  • apps/webapp/app/components/runs/v3/agent/AgentMessageView.tsx
  • apps/webapp/app/hooks/useAgentPageContext.ts
  • apps/webapp/app/presenters/v3/ApiAlertChannelPresenter.server.ts
  • apps/webapp/app/presenters/v3/reports/health/health-messages.ts
  • apps/webapp/app/presenters/v3/reports/health/health.ts
  • apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.server.ts
  • apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.agents.$agentParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts.new/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.apikeys/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.batches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.deployments/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.errors.$fingerprint/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.limits/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.prompts._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions.$sessionParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.test/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.waitpoints.tokens/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections.new/route.tsx
  • apps/webapp/app/routes/account.tokens/route.tsx
  • apps/webapp/app/routes/api.v1.dashboard-agent.alerts.$channelId.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.fired.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.jwt.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.repo.snapshot.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.waiting.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.workers.$tagName.ts
  • apps/webapp/app/routes/api.v1.queues.$queueParam.metrics.ts
  • apps/webapp/app/routes/resources.dashboard-agent.alerts.$channelId.unsubscribe.tsx
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.in.$.ts
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.ts
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam.spans.$spanParam/route.tsx
  • apps/webapp/app/routes/storybook.agent-ui/manifest.ts
  • apps/webapp/app/routes/storybook.agent-ui/route.tsx
  • apps/webapp/app/routes/storybook.callout/route.tsx
  • apps/webapp/app/services/dashboardAgentAlertContext.server.ts
  • apps/webapp/app/services/dashboardAgentAlertUnsubscribeToken.server.ts
  • apps/webapp/app/services/dashboardAgentHeadStart.server.ts
  • apps/webapp/app/services/dashboardAgentWatchAlerts.server.ts
  • apps/webapp/app/services/dashboardAgentWatchChecks.server.ts
  • apps/webapp/app/services/dashboardAgentWatchChecks.ts
  • apps/webapp/app/services/dashboardAgentWatchToken.server.ts
  • apps/webapp/app/services/dashboardAgentWatches.server.ts
  • apps/webapp/app/services/resolveTriggerUri.server.ts
  • apps/webapp/app/services/uatRoutePreamble.server.ts
  • apps/webapp/app/utils/handle.ts
  • apps/webapp/app/v3/alertsWorker.server.ts
  • apps/webapp/app/v3/featureFlags.ts
  • apps/webapp/app/v3/services/alerts/deliverAlert.server.ts
  • apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts
  • apps/webapp/package.json
  • apps/webapp/scripts/agent-ui-screenshots.ts
  • apps/webapp/seed-agent-examples-chats.mts
  • apps/webapp/seed-agent-examples.mts
  • apps/webapp/seed-queue-metrics.mts
  • apps/webapp/test/dashboardAgentHeadStart.test.ts
  • apps/webapp/test/dashboardAgentRoutes.test.ts
  • apps/webapp/test/dashboardAgentWatchChecks.test.ts
  • apps/webapp/test/dashboardAgentWatchToken.test.ts
  • apps/webapp/test/dashboardAgentWatches.test.ts
  • apps/webapp/test/reportHealth.test.ts
  • apps/webapp/test/resolveTriggerUri.test.ts
  • apps/webapp/test/seedAgentExamplesChats.test.ts
  • apps/webapp/test/waitingRunDiagnosis.test.ts
  • apps/webapp/vitest.config.ts
  • internal-packages/dashboard-agent-contracts/package.json
  • internal-packages/dashboard-agent-contracts/src/blocks.test.ts
  • internal-packages/dashboard-agent-contracts/src/blocks.ts
  • internal-packages/dashboard-agent-contracts/src/contracts.test.ts
  • internal-packages/dashboard-agent-contracts/src/evidence.ts
  • internal-packages/dashboard-agent-contracts/src/index.ts
  • internal-packages/dashboard-agent-contracts/src/intent.ts
  • internal-packages/dashboard-agent-contracts/src/page-context.ts
  • internal-packages/dashboard-agent-contracts/src/run-filters.ts
  • internal-packages/dashboard-agent-contracts/src/suggested-prompts.ts
  • internal-packages/dashboard-agent-contracts/src/trigger-uri.test.ts
  • internal-packages/dashboard-agent-contracts/src/trigger-uri.ts
  • internal-packages/dashboard-agent-contracts/src/watch.test.ts
  • internal-packages/dashboard-agent-contracts/src/watch.ts
  • internal-packages/dashboard-agent-contracts/tsconfig.json
  • internal-packages/dashboard-agent-contracts/vitest.config.ts
  • internal-packages/dashboard-agent-db/README.md
  • internal-packages/dashboard-agent-db/drizzle/0002_luxuriant_king_cobra.sql
  • internal-packages/dashboard-agent-db/drizzle/0003_famous_champions.sql
  • internal-packages/dashboard-agent-db/drizzle/meta/0002_snapshot.json
  • internal-packages/dashboard-agent-db/drizzle/meta/0003_snapshot.json
  • internal-packages/dashboard-agent-db/drizzle/meta/_journal.json
  • internal-packages/dashboard-agent-db/package.json
  • internal-packages/dashboard-agent-db/src/ids.ts
  • internal-packages/dashboard-agent-db/src/index.ts
  • internal-packages/dashboard-agent-db/src/queries.ts
  • internal-packages/dashboard-agent-db/src/schema.ts
  • internal-packages/dashboard-agent/GUIDEBOOK.md
  • internal-packages/dashboard-agent/PLAYBOOK.md
  • internal-packages/dashboard-agent/VERDICTS.md
  • internal-packages/dashboard-agent/package.json
  • internal-packages/dashboard-agent/src/dashboard-agent.eval.ts
  • internal-packages/dashboard-agent/src/dashboard-agent.test.ts
  • internal-packages/dashboard-agent/src/dashboard-agent.ts
  • internal-packages/dashboard-agent/src/index.ts
  • internal-packages/dashboard-agent/src/tool-schemas.ts
  • internal-packages/dashboard-agent/src/tools.ts
  • internal-packages/dashboard-agent/src/watch-tick.test.ts
  • internal-packages/dashboard-agent/src/watch-tick.ts
  • internal-packages/dashboard-agent/vitest.eval.config.ts
  • internal-packages/database/prisma/migrations/20260729120000_add_dashboard_agent_watch_alert_type/migration.sql
  • internal-packages/database/prisma/schema.prisma
  • internal-packages/emails/emails/alert-dashboard-agent-watch.tsx
  • internal-packages/emails/src/index.tsx
💤 Files with no reviewable changes (1)
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx
🚧 Files skipped from review as they are similar to previous changes (189)
  • .server-changes/dashboard-agent-watches.md
  • apps/webapp/app/components/dashboard-agent/investigate-prompts.test.ts
  • .server-changes/dashboard-agent-first-turn-error.md
  • .server-changes/queue-metrics-api.md
  • apps/webapp/app/routes/storybook.callout/route.tsx
  • .server-changes/remove-header-docs-buttons.md
  • apps/webapp/app/components/dashboard-agent/InvestigationCard.test.ts
  • apps/webapp/app/components/dashboard-agent/progress-line.test.ts
  • apps/webapp/app/components/dashboard-agent/tool-labels.ts
  • internal-packages/dashboard-agent-db/drizzle/0003_famous_champions.sql
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.ts
  • apps/webapp/app/components/dashboard-agent/page-context-types.ts
  • internal-packages/dashboard-agent-db/src/ids.ts
  • apps/webapp/app/components/dashboard-agent/page-label.test.ts
  • .server-changes/dashboard-agent-investigate.md
  • internal-packages/dashboard-agent-db/src/index.ts
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoWatchChips.tsx
  • internal-packages/dashboard-agent-db/package.json
  • apps/webapp/app/components/dashboard-agent/run-id.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.test/route.tsx
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/index.ts
  • internal-packages/dashboard-agent-db/drizzle/0002_luxuriant_king_cobra.sql
  • apps/webapp/vitest.config.ts
  • apps/webapp/app/presenters/v3/reports/health/health.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/index.ts
  • apps/webapp/.gitignore
  • apps/webapp/app/components/dashboard-agent/ReportView.test.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.waitpoints.tokens/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections._index/route.tsx
  • apps/webapp/app/components/dashboard-agent/message-order.test.ts
  • internal-packages/dashboard-agent-contracts/src/index.ts
  • apps/webapp/app/components/dashboard-agent/InvestigateButton.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsx
  • .server-changes/dashboard-agent-watch-alerts.md
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.errors.$fingerprint/route.tsx
  • internal-packages/dashboard-agent-contracts/package.json
  • apps/webapp/app/services/uatRoutePreamble.server.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/intents.ts
  • internal-packages/dashboard-agent/src/index.ts
  • apps/webapp/app/v3/alertsWorker.server.ts
  • apps/webapp/app/hooks/useAgentPageContext.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts/route.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx
  • apps/webapp/app/components/metrics/MiniLineChart.tsx
  • internal-packages/dashboard-agent/vitest.eval.config.ts
  • apps/webapp/app/components/dashboard-agent/DashboardAgentHeader.tsx
  • internal-packages/dashboard-agent-contracts/tsconfig.json
  • internal-packages/database/prisma/schema.prisma
  • apps/webapp/app/components/dashboard-agent/tool-labels.test.ts
  • apps/webapp/app/services/dashboardAgentAlertContext.server.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.apikeys/route.tsx
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam.spans.$spanParam/route.tsx
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.repo.snapshot.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions/route.tsx
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.ts
  • apps/webapp/package.json
  • apps/webapp/app/components/dashboard-agent/navigate-target.test.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.workers.$tagName.ts
  • apps/webapp/app/components/dashboard-agent/demo/index.ts
  • internal-packages/dashboard-agent-db/drizzle/meta/_journal.json
  • internal-packages/dashboard-agent-contracts/src/evidence.ts
  • internal-packages/dashboard-agent-contracts/src/intent.ts
  • internal-packages/dashboard-agent-contracts/src/page-context.ts
  • apps/webapp/test/dashboardAgentHeadStart.test.ts
  • apps/webapp/app/components/dashboard-agent/progress-line.ts
  • apps/webapp/app/components/dashboard-agent/view-blocks.ts
  • apps/webapp/app/components/dashboard-agent/WakeBanner.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoSuggestedPromptsRow.tsx
  • apps/webapp/app/components/dashboard-agent/DashboardAgentDraft.tsx
  • apps/webapp/app/components/primitives/Callout.tsx
  • apps/webapp/app/routes/account.tokens/route.tsx
  • apps/webapp/app/components/dashboard-agent/navigate-target.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions._index/route.tsx
  • apps/webapp/app/components/dashboard-agent/investigate-prompts.ts
  • apps/webapp/test/dashboardAgentWatchToken.test.ts
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoIntentBubble.tsx
  • apps/webapp/app/routes/api.v1.dashboard-agent.alerts.$channelId.ts
  • apps/webapp/app/utils/handle.ts
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoReportCard.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.deployments/route.tsx
  • internal-packages/dashboard-agent-contracts/vitest.config.ts
  • apps/webapp/app/components/dashboard-agent/watch-chips.test.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/reports.ts
  • apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts
  • internal-packages/dashboard-agent/package.json
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.batches/route.tsx
  • internal-packages/dashboard-agent-db/README.md
  • apps/webapp/test/reportHealth.test.ts
  • apps/webapp/app/components/dashboard-agent/DashboardAgentComposer.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions.$sessionParam/route.tsx
  • apps/webapp/test/resolveTriggerUri.test.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/chart.ts
  • apps/webapp/app/components/runs/v3/agent/AgentMessageView.tsx
  • internal-packages/emails/src/index.tsx
  • apps/webapp/app/components/dashboard-agent/dashboardAgentLauncher.tsx
  • internal-packages/dashboard-agent-contracts/src/run-filters.ts
  • apps/webapp/app/presenters/v3/ApiAlertChannelPresenter.server.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.test.ts
  • apps/webapp/app/presenters/v3/reports/health/health-messages.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts.new/route.tsx
  • internal-packages/dashboard-agent-contracts/src/trigger-uri.test.ts
  • apps/webapp/app/components/dashboard-agent/agent-badges.tsx
  • apps/webapp/app/services/dashboardAgentAlertUnsubscribeToken.server.ts
  • apps/webapp/app/services/dashboardAgentWatchToken.server.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.prompts._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables/route.tsx
  • internal-packages/dashboard-agent-contracts/src/watch.test.ts
  • apps/webapp/app/components/dashboard-agent/WatchChips.tsx
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.jwt.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsx
  • internal-packages/dashboard-agent-contracts/src/trigger-uri.ts
  • internal-packages/dashboard-agent-contracts/src/suggested-prompts.ts
  • internal-packages/emails/emails/alert-dashboard-agent-watch.tsx
  • apps/webapp/app/components/dashboard-agent/useTranscriptAutoScroll.ts
  • apps/webapp/app/components/dashboard-agent/report-block-adapter.test.ts
  • apps/webapp/app/components/dashboard-agent/view-catalog.tsx
  • apps/webapp/app/components/dashboard-agent/watch-chips.ts
  • apps/webapp/app/components/dashboard-agent/view-blocks.test.ts
  • apps/webapp/app/components/dashboard-agent/demo/demo.test.ts
  • apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts
  • apps/webapp/app/components/dashboard-agent/list-row.tsx
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/promotedPrompt.server.ts
  • apps/webapp/app/components/dashboard-agent/page-label.ts
  • apps/webapp/app/components/dashboard-agent/run-id.test.ts
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.ts
  • apps/webapp/app/services/dashboardAgentWatchChecks.server.ts
  • apps/webapp/seed-agent-examples-chats.mts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsx
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/messages.ts
  • apps/webapp/app/v3/featureFlags.ts
  • internal-packages/dashboard-agent-contracts/src/watch.ts
  • apps/webapp/app/services/dashboardAgentWatchAlerts.server.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/registry.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.waiting.ts
  • apps/webapp/app/components/dashboard-agent/chat-layout.test.ts
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.in.$.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.agents.$agentParam/route.tsx
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/watches.ts
  • apps/webapp/app/services/dashboardAgentWatches.server.ts
  • apps/webapp/app/services/dashboardAgentHeadStart.server.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.ts
  • apps/webapp/test/dashboardAgentWatchChecks.test.ts
  • apps/webapp/scripts/agent-ui-screenshots.ts
  • internal-packages/dashboard-agent/src/watch-tick.test.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.limits/route.tsx
  • apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts
  • apps/webapp/test/dashboardAgentRoutes.test.ts
  • apps/webapp/app/components/dashboard-agent/report-block-adapter.ts
  • apps/webapp/test/seedAgentExamplesChats.test.ts
  • apps/webapp/test/dashboardAgentWatches.test.ts
  • apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx
  • apps/webapp/app/components/dashboard-agent/WatchWakeToast.tsx
  • apps/webapp/app/components/dashboard-agent/message-order.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/page-context.ts
  • apps/webapp/app/routes/resources.dashboard-agent.alerts.$channelId.unsubscribe.tsx
  • apps/webapp/app/components/dashboard-agent/chat-layout.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs._index/route.tsx
  • apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
  • internal-packages/dashboard-agent/src/dashboard-agent.ts
  • apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.ts
  • apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.server.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/investigation.ts
  • apps/webapp/seed-agent-examples.mts
  • apps/webapp/app/components/dashboard-agent/DashboardAgentChat.tsx
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.ts
  • apps/webapp/app/components/dashboard-agent/demo/fixtures/blocks.ts
  • apps/webapp/app/components/dashboard-agent/ReportView.tsx
  • apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.fired.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections.new/route.tsx
  • apps/webapp/app/components/dashboard-agent/demo/components/DemoInvestigationCard.tsx
  • internal-packages/dashboard-agent-db/drizzle/meta/0002_snapshot.json
  • apps/webapp/app/services/resolveTriggerUri.server.ts
  • internal-packages/dashboard-agent-db/drizzle/meta/0003_snapshot.json
  • internal-packages/dashboard-agent/src/dashboard-agent.test.ts
  • internal-packages/dashboard-agent/src/dashboard-agent.eval.ts
  • apps/webapp/app/components/dashboard-agent/DashboardAgent.tsx
  • internal-packages/dashboard-agent/src/watch-tick.ts
  • apps/webapp/app/components/dashboard-agent/DashboardAgentHistory.tsx
  • apps/webapp/test/waitingRunDiagnosis.test.ts
  • apps/webapp/app/routes/storybook.agent-ui/route.tsx
  • internal-packages/dashboard-agent/src/tool-schemas.ts
  • apps/webapp/app/services/dashboardAgentWatchChecks.ts
  • internal-packages/dashboard-agent/src/tools.ts
  • internal-packages/dashboard-agent-db/src/queries.ts
  • apps/webapp/app/routes/api.v1.queues.$queueParam.metrics.ts

Comment on lines +231 to +246
if (run.queuedAt) {
// Canonical queue wait = startedAt - queuedAt; for a run that hasn't started, now - queuedAt.
const end = run.startedAt ?? now;
const ms = Math.max(0, end.getTime() - run.queuedAt.getTime());
waitingLabel = `queued for ${formatMs(ms)}`;
waitingBasis = "queued_at";
} else if (run.delayUntil && run.delayUntil.getTime() > now.getTime()) {
// A delayed run isn't in the queue yet — this is a schedule, NOT queue latency.
waitingLabel = `scheduled to start at ${run.delayUntil.toISOString()}`;
waitingBasis = "delay_until";
} else {
// No queuedAt to measure from. Report creation age and SAY that's what it is.
const ms = Math.max(0, (run.startedAt ?? now).getTime() - run.createdAt.getTime());
waitingLabel = `time from creation: ${formatMs(ms)}`;
waitingBasis = "created_at";
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

waitingLabel can misreport an overdue delay as "time from creation".

When delayUntil has already elapsed but the run hasn't been re-enqueued yet (queuedAt still null), the branch at Line 237 is skipped (since delayUntil.getTime() > now.getTime() is false) and control falls to the "time from creation" branch. This measures from createdAt, which can be well before delayUntil — overstating how long the run has effectively been stuck versus its actual overdue-delay wait.

🐛 Proposed fix
   if (run.queuedAt) {
     // Canonical queue wait = startedAt - queuedAt; for a run that hasn't started, now - queuedAt.
     const end = run.startedAt ?? now;
     const ms = Math.max(0, end.getTime() - run.queuedAt.getTime());
     waitingLabel = `queued for ${formatMs(ms)}`;
     waitingBasis = "queued_at";
   } else if (run.delayUntil && run.delayUntil.getTime() > now.getTime()) {
     // A delayed run isn't in the queue yet — this is a schedule, NOT queue latency.
     waitingLabel = `scheduled to start at ${run.delayUntil.toISOString()}`;
     waitingBasis = "delay_until";
+  } else if (run.delayUntil) {
+    // Delay has elapsed but the run hasn't been re-enqueued yet — measure from delayUntil,
+    // not createdAt, so a stale schedule window isn't blamed on this wait.
+    const ms = Math.max(0, (run.startedAt ?? now).getTime() - run.delayUntil.getTime());
+    waitingLabel = `overdue by ${formatMs(ms)}`;
+    waitingBasis = "delay_until";
   } else {
     // No queuedAt to measure from. Report creation age and SAY that's what it is.
     const ms = Math.max(0, (run.startedAt ?? now).getTime() - run.createdAt.getTime());
     waitingLabel = `time from creation: ${formatMs(ms)}`;
     waitingBasis = "created_at";
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (run.queuedAt) {
// Canonical queue wait = startedAt - queuedAt; for a run that hasn't started, now - queuedAt.
const end = run.startedAt ?? now;
const ms = Math.max(0, end.getTime() - run.queuedAt.getTime());
waitingLabel = `queued for ${formatMs(ms)}`;
waitingBasis = "queued_at";
} else if (run.delayUntil && run.delayUntil.getTime() > now.getTime()) {
// A delayed run isn't in the queue yet — this is a schedule, NOT queue latency.
waitingLabel = `scheduled to start at ${run.delayUntil.toISOString()}`;
waitingBasis = "delay_until";
} else {
// No queuedAt to measure from. Report creation age and SAY that's what it is.
const ms = Math.max(0, (run.startedAt ?? now).getTime() - run.createdAt.getTime());
waitingLabel = `time from creation: ${formatMs(ms)}`;
waitingBasis = "created_at";
}
if (run.queuedAt) {
// Canonical queue wait = startedAt - queuedAt; for a run that hasn't started, now - queuedAt.
const end = run.startedAt ?? now;
const ms = Math.max(0, end.getTime() - run.queuedAt.getTime());
waitingLabel = `queued for ${formatMs(ms)}`;
waitingBasis = "queued_at";
} else if (run.delayUntil && run.delayUntil.getTime() > now.getTime()) {
// A delayed run isn't in the queue yet — this is a schedule, NOT queue latency.
waitingLabel = `scheduled to start at ${run.delayUntil.toISOString()}`;
waitingBasis = "delay_until";
} else if (run.delayUntil) {
// Delay has elapsed but the run hasn't been re-enqueued yet — measure from delayUntil,
// not createdAt, so a stale schedule window isn't blamed on this wait.
const ms = Math.max(0, (run.startedAt ?? now).getTime() - run.delayUntil.getTime());
waitingLabel = `overdue by ${formatMs(ms)}`;
waitingBasis = "delay_until";
} else {
// No queuedAt to measure from. Report creation age and SAY that's what it is.
const ms = Math.max(0, (run.startedAt ?? now).getTime() - run.createdAt.getTime());
waitingLabel = `time from creation: ${formatMs(ms)}`;
waitingBasis = "created_at";
}

… is one sentence

Latest-wins now applies across the whole transcript, not just within one
tool call — the in_progress working copy disappears when the verdict
revision renders. The prompt bans list-shaped prose after the verdict
card: everything list-shaped belongs on the card.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal-packages/dashboard-agent/src/tool-schemas.ts (1)

547-559: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Align the capability instructions with the new mutating tools.

The prompt now exposes schedule_watch, create_alert, and delete_alert, but it still describes the toolset as read-only and later says the agent cannot change anything. This contradiction can make the agent refuse supported watch/alert actions or incorrectly direct users to the dashboard. Update the blanket capability text to distinguish read-only data tools from these explicitly authorized mutations.

🧹 Nitpick comments (1)
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx (1)

351-368: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Memoize the transcript-derived winner map.

Line 357 creates a new Map on every render, and Line 368 passes it to memoized turns; activity-only updates therefore rerender the entire transcript and rescan all parts. Memoize stripped and its winners from messages.

Proposed change
-  const stripped = messages.map(stripStepParts);
-
-  const investigationWinners = winningInvestigationOccurrences(stripped);
+  const { stripped, investigationWinners } = useMemo(() => {
+    const stripped = messages.map(stripStepParts);
+    return {
+      stripped,
+      investigationWinners: winningInvestigationOccurrences(stripped),
+    };
+  }, [messages]);

As per coding guidelines, useMemo is appropriate for expensive derived data and stable references required by dependency arrays.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ae8860fd-cece-44f8-b032-c969b4234488

📥 Commits

Reviewing files that changed from the base of the PR and between fd5006e and 7abce81.

📒 Files selected for processing (2)
  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • internal-packages/dashboard-agent/src/tool-schemas.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (33)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
  • GitHub Check: sdk-compat / Node.js 22.23 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Node.js 24.18 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Bun Runtime
  • GitHub Check: sdk-compat / Node.js 26.4 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Node.js 20.20 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-ubuntu-latest-x64-4x - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - pnpm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-ubuntu-latest-x64-4x - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - npm)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
  • GitHub Check: sdk-compat / Cloudflare Workers
  • GitHub Check: sdk-compat / Deno Runtime
  • GitHub Check: runops-guard / runops-guard
  • GitHub Check: internal / 🧪 Unit Tests: Internal
  • GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
  • GitHub Check: code-quality / code-quality
  • GitHub Check: 🛡️ E2E Auth Tests (full)
  • GitHub Check: Analyze (javascript-typescript)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead

**/*.{ts,tsx}: Prefer static imports over dynamic import(); use dynamic imports only for unresolvable circular dependencies, genuine performance code splitting, or conditional runtime loading.
Import Trigger.dev tasks from @trigger.dev/sdk; never use @trigger.dev/sdk/v3 or deprecated client.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with // @Crumbs or blocks with `// `#region` `@crumbs, and strip them before merging.

Files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • internal-packages/dashboard-agent/src/tool-schemas.ts
{packages/core,apps/webapp}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use zod for validation in packages/core and apps/webapp

Files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use function declarations instead of default exports

Files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • internal-packages/dashboard-agent/src/tool-schemas.ts
apps/webapp/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)

apps/webapp/**/*.{ts,tsx}: Access environment variables through the env export of env.server.ts instead of directly accessing process.env
Use subpath exports from @trigger.dev/core package instead of importing from the root @trigger.dev/core path

Do not reintroduce the removed v1 execution path; RunEngineVersion.V1 branches may only reject or finalize gracefully so v3 clients receive a clean 4xx, never a 5xx.

Files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
apps/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

For apps, use typecheck for verification and never use build as the correctness check.

Files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
apps/webapp/app/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)

apps/webapp/app/**/*.{ts,tsx}: For dashboard changes, visually verify the running Remix app with Chrome DevTools MCP, using snapshots, screenshots, interaction, and console-message checks as appropriate.
Use useCallback and useMemo only for context provider values, expensive derived data used as a dependency, or stable references required by dependency arrays; do not wrap ordinary event handlers or trivial computations.
Use named constants for sentinel or placeholder values instead of scattering raw string literals across comparisons.

Files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)

**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries

Files:

  • internal-packages/dashboard-agent/src/tool-schemas.ts
internal-packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

For internal packages, use typecheck for verification and never use build as the correctness check.

Files:

  • internal-packages/dashboard-agent/src/tool-schemas.ts
🧠 Learnings (18)
📚 Learning: 2026-02-11T16:37:32.429Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3019
File: apps/webapp/app/components/primitives/charts/Card.tsx:26-30
Timestamp: 2026-02-11T16:37:32.429Z
Learning: In projects using react-grid-layout, avoid relying on drag-handle class to imply draggability. Ensure drag-handle elements only affect dragging when the parent grid item is configured draggable in the layout; conditionally apply cursor styles based on the draggable prop. This improves correctness and accessibility.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-07-28T21:57:20.061Z
Learnt from: samejr
Repo: triggerdotdev/trigger.dev PR: 4411
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.team/route.tsx:818-843
Timestamp: 2026-07-28T21:57:20.061Z
Learning: When using Radix UI `DialogClose` with `asChild` (e.g., Trigger.dev dashboard components), note that it injects `type="button"` into its child via `Slot`. If the child is a local `Button` that forwards its `type` prop to the native `<button>`, then placing it inside a `<form>` will *not* submit unless you explicitly set `type="submit"` (or otherwise override the injected type / wire up submission behavior). Review form actions to ensure the intended submit vs non-submit behavior is preserved.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • internal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • internal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • internal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • internal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-06-13T19:53:13.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3937
File: packages/trigger-sdk/skills/realtime-and-frontend/SKILL.md:258-260
Timestamp: 2026-06-13T19:53:13.759Z
Learning: When reviewing code that uses `trigger.dev/react-hooks`’s `useRealtimeRun`, preserve the call signature where the first argument is the full realtime handle object (not `handle.id`). This is intentional to maintain type-safety and is consistent with the official docs; do not suggest changing the first argument from the handle object to `handle.id`.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • internal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-06-17T17:13:49.929Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3948
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions.$bulkActionParam/route.tsx:48-62
Timestamp: 2026-06-17T17:13:49.929Z
Learning: In triggerdotdev/trigger.dev, within `dashboardLoader`/`dashboardAction` (or similar context resolver code) whenever you resolve an organization ID from an organization slug for RBAC/enterprise authorization scope, always read from the primary Prisma client (`prisma`), not `$replica`. Using `$replica` can hit replica-lag and cause the RBAC lookup/authorization to run without the correct org scope (bypassing intended role enforcement). Implement the slug→org lookup with `prisma.organization.findFirst(...)` (or equivalent primary-client query) and add an inline comment documenting why the primary client is required (replica lag could lead to unscoped RBAC checks).

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • internal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-06-23T13:04:21.413Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4023
File: apps/webapp/app/services/upsertBranch.server.ts:14-18
Timestamp: 2026-06-23T13:04:21.413Z
Learning: In TypeScript, it’s valid to `import { type X }` and then use `typeof X` in a type-only position, e.g. `type Alias = z.infer<typeof X>`. The `type` modifier suppresses the runtime import, but the type checker still has the full exported type so `z.infer<typeof X>` can resolve correctly. In code reviews, don’t flag this as a TypeScript compile error as long as `typeof X` is used in a type context (e.g., with `z.infer`, `type` aliases, generics), not as a runtime value.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
  • internal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-04-16T14:21:15.229Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3368
File: apps/webapp/app/components/logs/LogsTaskFilter.tsx:135-163
Timestamp: 2026-04-16T14:21:15.229Z
Learning: When rendering lists of task registry items in apps/webapp (e.g., <SelectItem /> rows) and using `key={item.slug}`, do not flag it as potentially non-unique. In trigger.dev’s `TaskIdentifier` table, the DB constraint `@unique([runtimeEnvironmentId, slug])` guarantees `slug` is unique within a given runtime environment, so `item.slug` is safe as the React key as long as the list is derived from that registry/constraint (and not from a legacy query that could produce duplicate slugs).

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-05-08T21:00:20.973Z
Learnt from: samejr
Repo: triggerdotdev/trigger.dev PR: 3538
File: apps/webapp/app/components/primitives/Resizable.tsx:60-78
Timestamp: 2026-05-08T21:00:20.973Z
Learning: In the triggerdotdev/trigger.dev codebase, treat Zod as a boundary validation tool (API handlers, request/response validation, and storage/DB read/write validation), not as inline render-time validation inside React components/primitive UI code. For render-time guards, prefer small manual type-narrowing checks (e.g., a short predicate like ~10–20 lines) over importing Zod into UI primitives, to avoid per-render schema-parse overhead and unnecessary abstraction. Use the manual guard approach unless you truly need schema validation at a boundary; only then introduce Zod.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-25T18:21:55.847Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/invite-resend.tsx:0-0
Timestamp: 2026-06-25T18:21:55.847Z
Learning: In the triggerdotdev/trigger.dev Zod 4 migration, avoid importing from the root package `conform-to/zod` in webapp code. It can resolve to the Zod 3 build and may crash at module load under Zod 4. When reviewing TypeScript/TSX files in `apps/webapp`, prefer importing from the Zod 4 subpath `conform-to/zod/v4` for Zod 4-compatible schemas/types.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-05-12T21:04:05.815Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3542
File: apps/webapp/app/components/sessions/v1/SessionStatus.tsx:1-3
Timestamp: 2026-05-12T21:04:05.815Z
Learning: In this Remix + TypeScript codebase, do not flag a server/client boundary violation when a file imports only types from a module matching `*.server`.

Specifically, it’s safe to import types using `import type { Foo } from "*.server"` or `import { type Foo } from "*.server"` because TypeScript erases type-only imports at compile time and they emit no JavaScript, so they won’t cross the Remix server/client bundle boundary.

Only raise the boundary concern for value imports (e.g., `import { Foo }` without `type`, or `import Foo`), since those produce JavaScript output.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-25T18:21:51.905Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/invite-revoke.tsx:0-0
Timestamp: 2026-06-25T18:21:51.905Z
Learning: During the Zod v4 migration in the triggerdotdev/trigger.dev webapp, ensure any imports from `conform-to/zod` use the Zod-4 subpath: `conform-to/zod/v4` (e.g., `import { parseWithZod } from "conform-to/zod/v4"`). Do not import from the package root `conform-to/zod`, because it is the Zod 3 implementation and may load Zod-3-only symbols (e.g., `ZodBranded`, `ZodEffects`), which can throw at module load (notably with `zod4.4.3`). This should be enforced across `apps/webapp/**/*` where helpers like `parseWithZod` and `conformZodMessage` are used.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-07-03T17:10:21.498Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 4148
File: apps/webapp/app/models/orgMember.server.ts:149-168
Timestamp: 2026-07-03T17:10:21.498Z
Learning: In triggerdotdev/trigger.dev, `User.email` (Prisma schema: `internal-packages/database/prisma/schema.prisma`) currently does NOT use `citext` and does NOT have a `lower(email)` functional unique index. Therefore, do not introduce Prisma queries like `where: { email: { equals: <value>, mode: "insensitive" } }` (or any case-insensitive lookup) against `User.email`, because it can force sequential scans of the `users` table under load. During review, ensure email is normalized (e.g., lowercased/trimmed) before both writes and subsequent lookups, and if true case-insensitive behavior/uniqueness is required, implement it via a separate app-wide migration (e.g., switch to `citext` and/or add a functional unique index with backfill) rather than bolting it onto individual feature PRs.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-25T18:21:54.729Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/confirm-basic-details.tsx:0-0
Timestamp: 2026-06-25T18:21:54.729Z
Learning: For Remix + TypeScript files that use Conform v1 (conform-to/react) and its getInputProps helper, when you intend to suppress the helper-provided default value for non-checkbox/non-radio inputs (e.g., hidden inputs managed via an explicit value prop), use the Conform v1 option key `value: false`. Do not recommend `defaultValue: false` here, because `defaultValue` is not a valid option key for these input types in Conform v1 typings.

Applied to files:

  • apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-04T18:16:35.386Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3836
File: apps/supervisor/src/backpressure/backpressureMonitor.ts:3-5
Timestamp: 2026-06-04T18:16:35.386Z
Learning: When reviewing TypeScript in this repo, apply the rule “prefer type aliases over interfaces” only to data/object shapes and union/intersection type modeling. If an interface is being used as a behavioral contract for collaborators to implement (e.g., method-shape interfaces that define required behavior, such as `BackpressureLogger` / `BackpressureSignalSource` in `apps/supervisor/src/backpressure/backpressureMonitor.ts`), keep it as an `interface` and do not flag it as a type-alias-vs-interface violation.

Applied to files:

  • internal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-06-09T17:58:04.699Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 3879
File: apps/webapp/app/models/vercelIntegration.server.ts:619-630
Timestamp: 2026-06-09T17:58:04.699Z
Learning: In this codebase, outbound raw `fetch` calls should typically rely on Node/undici’s default request timeout (about ~300s) rather than adding a per-call `AbortController` + `setTimeout` wrapper inside individual functions (e.g. in files like `apps/webapp/app/models/vercelIntegration.server.ts`). During code review, do not flag the absence of a per-call timeout on a single `fetch` as an issue; if per-call timeouts are needed, they should be implemented via a codebase-wide convention (e.g., a shared fetch wrapper or documented pattern) rather than ad-hoc per-function changes.

Applied to files:

  • internal-packages/dashboard-agent/src/tool-schemas.ts
🔇 Additional comments (1)
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx (1)

99-146: LGTM!

Also applies to: 245-287

…s pill wins

The card's progress line is now the same pill the in-flight tools use,
and while an in_progress investigation card is on screen the concurrent
tool pill is suppressed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants